C#客户端TCP/IP连接如何管理

avatar
作者
筋斗云
阅读量:0

在C#中,使用TCP/IP连接的客户端可以通过System.Net.Sockets命名空间中的TcpClientNetworkStream类进行管理

  1. 引入命名空间:
using System.Net; using System.Net.Sockets; using System.IO; 
  1. 创建一个TcpClient实例并连接到服务器:
TcpClient client = new TcpClient(); await client.ConnectAsync("server_ip_address", server_port); 
  1. 获取与服务器的网络流(NetworkStream):
NetworkStream stream = client.GetStream(); 
  1. 发送数据到服务器:
string message = "Hello, Server!"; byte[] data = Encoding.UTF8.GetBytes(message); await stream.WriteAsync(data, 0, data.Length); 
  1. 从服务器接收数据:
byte[] buffer = new byte[1024]; int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); string response = Encoding.UTF8.GetString(buffer, 0, bytesRead); 
  1. 关闭连接:
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连接。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!