C# 创建TCP客户端

C# 创建TCP客户端

private Socket socket = null;
public bool ConnectState = false;
//Socket客户端 创建并连接
public bool Connect(string ip, int port)
{
   socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
   EndPoint point = new IPEndPoint(IPAddress.Parse(ip), port);
   IAsyncResult connResult = socket.BeginConnect(point, null, null);
   //连接超时为500ms
   connResult.AsyncWaitHandle.WaitOne(500, true);
   if (connResult.IsCompleted && socket.Connected)
   {
       ConnectState = true;
       //数据接收
       Task.Run(() => { Receive(); });
       return true;
   }
   else
   {
       ConnectState = false;
       return false;
   }
}

你可能感兴趣的:(C#,c#,tcp/ip,网络)