在C#中,TcpListener
類用于創建一個TCP服務器,監聽來自客戶端的連接請求。以下是創建一個簡單的TCP服務器的步驟:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
TcpListener
實例,指定監聽的IP地址和端口號:IPHostAddress ipAddress = IPAddress.Any; // 監聽所有可用的網絡接口
int port = 12345; // 選擇一個端口號
TcpListener listener = new TcpListener(ipAddress, port);
listener.Start();
Console.WriteLine("Server is listening on port " + port);
while (true)
{
// 接受客戶端連接請求
TcpClient client = await listener.AcceptTcpClientAsync();
Console.WriteLine("Client connected: " + client.Client.RemoteEndPoint.ToString());
// 處理客戶端請求
Task.Run(() => HandleClient(client));
}
private static async Task HandleClient(TcpClient client)
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead;
// 讀取客戶端發送的數據
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
string data = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received from client: " + data);
// 響應客戶端
string response = "Hello from server!";
byte[] responseBytes = Encoding.UTF8.GetBytes(response);
await stream.WriteAsync(responseBytes, 0, responseBytes.Length);
}
// 關閉客戶端連接
client.Close();
Console.WriteLine("Client disconnected: " + client.Client.RemoteEndPoint.ToString());
}
Main
方法中啟動服務器:static void Main(string[] args)
{
// 創建TCP監聽器
TcpListener listener = new TcpListener(IPAddress.Any, 12345);
// 開始監聽客戶端連接請求
listener.Start();
Console.WriteLine("Server is listening on port 12345");
// 使用異步方法接受客戶端連接
while (true)
{
TcpClient client = await listener.AcceptTcpClientAsync();
Console.WriteLine("Client connected: " + client.Client.RemoteEndPoint.ToString());
// 處理客戶端請求
Task.Run(() => HandleClient(client));
}
}
這個示例創建了一個簡單的TCP服務器,監聽端口12345,并在接收到客戶端連接請求時發送一條響應消息。你可以根據需要修改這個示例,以滿足你的具體需求。