在C#中,使用TCP/IP连接的客户端可以通过System.Net.Sockets
命名空间中的TcpClient
和NetworkStream
类进行管理
using System.Net;
using System.Net.Sockets;
using System.IO;
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);
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连接。