c#中tcplistener的用法是什么

c#
小億
217
2024-03-16 20:02:56

在C#中,TcpListener類(lèi)用于創(chuàng)建一個(gè)TCP服務(wù)器,用于偵聽(tīng)傳入的TCP連接請(qǐng)求并處理它們。以下是TcpListener類(lèi)的一般用法:

  1. 創(chuàng)建TcpListener實(shí)例:
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 8080);
  1. 開(kāi)始偵聽(tīng)傳入的連接請(qǐng)求:
server.Start();
  1. 接受傳入連接請(qǐng)求并返回一個(gè)TcpClient實(shí)例用于與客戶(hù)端通信:
TcpClient client = server.AcceptTcpClient();
  1. 通過(guò)TcpClient實(shí)例進(jìn)行通信,發(fā)送和接收數(shù)據(jù):
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);
  1. 關(guān)閉TcpListener和TcpClient實(shí)例:
client.Close();
server.Stop();

這是TcpListener類(lèi)的基本用法,您可以根據(jù)需要進(jìn)行更多的配置和處理。

0