阅读量:0
在C#中,使用TCP/IP连接的客户端可以通过System.Net.Sockets
命名空间中的TcpClient
和NetworkStream
类进行管理
- 引入命名空间:
using System.Net; using System.Net.Sockets; using System.IO;
- 创建一个TcpClient实例并连接到服务器:
TcpClient client = new TcpClient(); await client.ConnectAsync("server_ip_address", server_port);
- 获取与服务器的网络流(NetworkStream):
NetworkStream stream = client.GetStream();
- 发送数据到服务器:
string message = "Hello, Server!"; byte[] data = Encoding.UTF8.GetBytes(message); await stream.WriteAsync(data, 0, data.Length);
- 从服务器接收数据:
byte[] buffer = new byte[1024]; int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
- 关闭连接:
stream.Close(); client.Close();
将上述代码片段组合成一个完整的方法:
public async Task ConnectToServerAsync() { try { TcpClient client = new TcpClient(); await client.ConnectAsync("server_ip_address", server_port); NetworkStream stream = client.GetStream(); string message = "Hello, Server!"; byte[] data = Encoding.UTF8.GetBytes(message); await stream.WriteAsync(data, 0, data.Length); byte[] buffer = new byte[1024]; int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); string response = Encoding.UTF8.GetString(buffer, 0, bytesRead); Console.WriteLine("Server response: " + response); stream.Close(); client.Close(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
要使用此方法,请确保将"server_ip_address"和server_port替换为实际的服务器IP地址和端口号。然后,在程序中调用ConnectToServerAsync()
方法以异步方式建立TCP/IP连接。