在C#中,您可以使用TcpListener
類創建一個TCP監聽器
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class TcpListenerExample
{
static void Main(string[] args)
{
// 設置監聽的IP地址和端口號
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 8080;
// 創建一個TcpListener實例
TcpListener listener = new TcpListener(ipAddress, port);
// 開始監聽連接
listener.Start();
Console.WriteLine("TCP Listener started on {0}", ipAddress + ":" + port);
try
{
while (true)
{
// 等待客戶端連接
Console.Write("Waiting for a client connection...");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Client connected!");
// 處理客戶端請求
HandleClientRequest(client);
// 關閉客戶端連接
client.Close();
Console.WriteLine("Client disconnected.");
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
// 停止監聽
listener.Stop();
Console.WriteLine("TCP Listener stopped.");
}
}
static void HandleClientRequest(TcpClient client)
{
// 讀取客戶端發送的數據
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string request = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received message: " + request);
// 響應客戶端
string response = "Hello from the server!";
byte[] responseBytes = Encoding.UTF8.GetBytes(response);
stream.Write(responseBytes, 0, responseBytes.Length);
Console.WriteLine("Sent response: " + response);
}
}
這個示例中,我們首先創建一個TcpListener
實例,指定監聽的IP地址和端口號。然后使用Start()
方法開始監聽連接。在循環中,我們等待客戶端連接,接受連接后調用HandleClientRequest()
方法處理客戶端請求。最后,關閉客戶端連接并繼續監聽新的連接。