在C#中,TcpListener類(lèi)用于創(chuàng)建一個(gè)TCP服務(wù)器,用于偵聽(tīng)傳入的TCP連接請(qǐng)求并處理它們。以下是TcpListener類(lèi)的一般用法:
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 8080);
server.Start();
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
// 發(fā)送數(shù)據(jù)
byte[] data = Encoding.ASCII.GetBytes("Hello, client!");
stream.Write(data, 0, data.Length);
// 接收數(shù)據(jù)
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
client.Close();
server.Stop();
這是TcpListener類(lèi)的基本用法,您可以根據(jù)需要進(jìn)行更多的配置和處理。