[英]How to move on to next client in C# tcp server correctly?
tcpListener = new TcpListener(IPAddress.Any, 6007);
tcpListener.Start();
while (true)
{
TcpClient client = tcpListener.AcceptTcpClient();
sw = new StreamWriter(client.GetStream());
sr = new StreamReader(client.GetStream());
while(true)
parseRequest(sr.ReadLine());
}
This is essentially the code I am using for a C# tcp server. 本质上,这是我用于C#tcp服务器的代码。 The server needs to handle multiple connections, but not simultaneously, so it can work with one client, and when that client disconnects continue on to the next client.
服务器需要处理多个连接,但不能同时处理,因此它可以与一个客户端一起使用,并且当该客户端断开连接时,继续处理下一个客户端。 The client can send a variable amount of messages, and the server needs to process these messages.
客户端可以发送可变数量的消息,服务器需要处理这些消息。
The problem is when the first client disconnects it never connects to the next client. 问题是当第一个客户端断开连接时,它永远不会连接到下一个客户端。 I tried adding code in my second while loop to check "if (!Client.Connected) break; " but Connected always returned true, even after my client application had closed out.
我尝试在第二个while循环中添加代码以检查“ if(!Client.Connected)break;”,但即使我的客户端应用程序已关闭,Connected始终返回true。 What can I do to be able to connect to the second client after the first has disconnected?
在第一个客户端断开连接后,我该怎么做才能连接到第二个客户端?
You need to start a new thread or register a new listener for each accepted socket, instead of processing it entirely in the same loop that is accepting new clients. 您需要为每个接受的套接字启动一个新线程或注册一个新的侦听器,而不是完全在接受新客户端的同一循环中对其进行处理。 The accept loop should do nothing else.
accept循环应该什么都不做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.