我的服务器端有以下代码:
// 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。
答案 0 :(得分:2)
使用AcceptTcpClient
而不是Pending
,它会起作用。
为什么你要做的就是制作这些步骤:
简而言之,这不是因为你启动一个线程,内部的一些随机指令立即被执行。线程的关键在于:它将在稍后执行。
如果您希望有办法停止收听过程,请使用WaitHandles
:
// In your class somewhere stopEvent is a ManualResetEvent
while(true)
{
var asyncResult = listener.BeginAcceptTcpClient(null, null);
var waitHandles = new [] { stopEvent, asyncResult.AsyncWaitHandle };
var waitResult = WaitHandle.WaitAny(waitHandles);
if (waitResult == 0) return;
var client = EndAcceptTcpClient(asyncResult);
// Create thread to speak with this client
}
您想要停止线程的方法只需要stopEvent.Set()