C#实现 Socket客户端通信
时间: 2024-06-18 07:03:16 浏览: 209
C# 实现 Socket 客户端通信的步骤如下:
1. 创建 Socket 对象,并指定服务器的 IP 地址和端口号。
```
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse("服务器IP地址");
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 端口号);
clientSocket.Connect(ipEndPoint);
```
2. 向服务器发送数据。
```
string sendData = "Hello World!";
byte[] data = Encoding.UTF8.GetBytes(sendData);
clientSocket.Send(data);
```
3. 接收服务器返回的数据。
```
byte[] receiveData = new byte[1024];
int length = clientSocket.Receive(receiveData);
string receiveMessage = Encoding.UTF8.GetString(receiveData, 0, length);
Console.WriteLine(receiveMessage);
```
4. 关闭 Socket 连接。
```
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
```
阅读全文