我在服务器端有以下代码:
// Bind to a specific local port number (SERVER_PORT) and any local IP address.
m_tlServer = new TcpListener(IPAddress.Any, SERVER_PORT);
// Start listening for connection attempts.
m_tlServer.Start();
// Start accepting new clients.
// Sleep until a new client(s) will try to connect to the server.
while (!m_bStopThread)
{
if (!m_tlServer.Pending())
{
// Sleep and try again.
Thread.Sleep(LISTENING_SLEEP_TIME);
continue;
}
else
{
// Accept a new client in a new thread.
Thread newthread = new Thread(new ThreadStart(HandleNewConnection));
newthread.Start();
}
}
我的问题是当客户端尝试连接服务器时,方法
Pending
会多次返回true
(通常是4次),并且会创建多个线程。我尝试用使用AcceptTcpClient
方法的循环替换该while循环(不知道是否有任何连接尝试),这样可以正常工作。因此,我认为问题是由Pending
方法引起的。有人能帮我吗?谢谢,Ofer。
m_stop
变量,但框架在这种情况下的操作基本上是在一个线程池线程中执行我编写的代码并调用您的回调。在像这样的简单情况下,结果是相同的。但真正的异步IO更加强大,因为同一线程可以等待新客户端、等待所有客户端上的新数据包到达以及等待数据包被发送...(然后你运行JavaScript而不是C#,并称其为node.js) - Julien Roncaglia