You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
SocketStudy/SocketStudy/Client/PClientSocket.cs

51 lines
1.1 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Client
{
class PClientSocket
{
private readonly int BUFF_SIZE = 8192;
private Socket sock;
private IPEndPoint endPoint;
public PClientSocket(string ip, int port)
{
// create socket
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
}
public void Connect()
{
// connect end point
sock.Connect(endPoint);
string cmd = string.Empty;
byte[] receiveBuff = new byte[BUFF_SIZE];
Console.WriteLine("Connected... Press Q to exit.");
while ((cmd = Console.ReadLine()) != "Q")
{
byte[] buff = Encoding.UTF8.GetBytes(cmd);
// send data
sock.Send(buff, SocketFlags.None);
// receive data
int n = sock.Receive(receiveBuff);
string data = Encoding.UTF8.GetString(receiveBuff, 0, n);
Console.WriteLine($"Received: {data}");
}
sock.Close();
}
}
}