TCP通讯客户端的一个简单案例
注意:客户端不需要绑定ip和端口,只需要和服务端建立连接
static void Main(string[] args) { Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5000)); //服务端向客户端发送消息,只需要向服务端建立连接 byte[] data = new byte[1024]; int count = clientSocket.Receive(data); string msg = System.Text.Encoding.UTF8.GetString(data, 0, count); Console.WriteLine(msg); //向服务端发送数据 clientSocket.Send(System.Text.Encoding.UTF8.GetBytes("Hello Server,My is Cilent")); }