温馨提示×

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

c#
小樊
115
2024-09-14 23:34:28
栏目: 编程语言

在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连接。

0