[英]How TCP/IP server listens to several clients?
我正在使用 GSM/GPRS 調制解調器建立一個小型 tcp/ip 連接,我有一台運行服務器(監聽器)程序的服務器 PC,並且有幾個(超過 100 個)調制解調器位於不同的地方,它們發送小數據包在特定時期向服務器發送數據。
我已經用一個客戶端測試了系統,但是如何用多個客戶端測試它? 我的服務器將如何響應多個客戶端?
這是我的服務器代碼:
private TcpListener tcpListener;
private Thread listenThread;
public static TcpClient client;
public Form1()
{
InitializeComponent();
this.tcpListener = new TcpListener(IPAddress.Any, 2020);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
//TcpClient client = new TcpClient(servername or ip , port);
//IpEndPoint ipend = tcpClient.RemoteEndPoint;
//Console.WriteLine(IPAddress.Parse(ipend.Address.ToString());
//label3.Text = IPAddress.Parse(((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString()).ToString();
SetControlPropertyThreadSafe(label3, "Text", IPAddress.Parse(((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString()).ToString());
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
//System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
string received_text = encoder.GetString(message, 0, bytesRead).ToString();
SetControlPropertyThreadSafe(label1, "Text", received_text);
if (received_text == "cmdtim")
{
SendData(DateTime.Now.ToString());
}
}
tcpClient.Close();
}
如您所見,我為監聽客戶端創建了一個單獨的線程,我如何監聽多個客戶端?
我應該為每個客戶創建一個線程嗎?
我不知道我每一刻會有多少個客戶端,服務器在監聽特定客戶端時會緩沖其他客戶端的數據嗎?
監聽多個客戶並發送所有數據的最佳策略是什么?
一些建議:
消除:
public static TcpClient client;
代替:
client = this.tcpListener.AcceptTcpClient();
和
TcpClient client = this.tcpListener.AcceptTcpClient();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.