C# socket TCP 通信
Server:
void Main() { var maxWaitingRequest = 10; var localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); localSocket.Bind(new IPEndPoint(IPAddress.Any, 40000)); localSocket.Listen(maxWaitingRequest); while (true) { var remoteSocket = localSocket.Accept(); var remoteIP = (IPEndPoint)remoteSocket.RemoteEndPoint; Console.WriteLine("A new connection from {0}:{1} at {2}", remoteIP.Address.ToString(), remoteIP.Port.ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); ThreadPool.QueueUserWorkItem(acceptedConnectionHandler, remoteSocket); } } static void acceptedConnectionHandler(object p) { var remoteSocket = (Socket)p; remoteSocket.Send(System.Text.Encoding.Default.GetBytes("Hi client!")); var data = new List<byte>(); var dataBlock = new byte[1024]; while (true) { var read = remoteSocket.Receive(dataBlock); data.AddRange(dataBlock.Take(read)); if (read <= dataBlock.Length && data.Count > 0) { Console.WriteLine(System.Text.Encoding.Default.GetString(data.ToArray())); data.Clear(); } } }
Client:
void Main() { var localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var localEP = new IPEndPoint(IPAddress.Any, 20000); localSocket.Bind(localEP); localSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 40000)); ThreadPool.QueueUserWorkItem(connectedConnectionHandler,localSocket); while(true) Thread.Sleep(100); } public static void connectedConnectionHandler(object p) { var localSocket = (Socket)p; var data = new List<byte>(); var dataBlock = new byte[1024]; while (true) { var read = localSocket.Receive(dataBlock); data.AddRange(dataBlock.Take(read)); if (read <= dataBlock.Length && data.Count > 0) { Console.WriteLine(System.Text.Encoding.Default.GetString(data.ToArray())); data.Clear(); localSocket.Send(System.Text.Encoding.Default.GetBytes("Hi server!")); } } }
桂棹兮兰桨,击空明兮溯流光。