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