我正在使用套接字侦听器从客户端接收数据。
当服务器正在侦听连接时,是否可以替换无限循环while (true)
?
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)//infinite loop
{
}
答案 0 :(得分:4)
假设你的while循环是这样的:
while(true)
{
Socket workerSocket = listener.Accept();
DoSomethingWithSocket(workerSocket);
}
然后是,用
替换while(true)
listener.BeginAccept(new AsyncCallback(OnClientConnect), null);
然后添加方法
public void OnClientConnect(IAsyncResult asyn)
{
Socket workerSocket = Listener.EndAccept(asyn);
Listener.BeginAccept(new AsyncCallback(OnClientConnect), null);
DoSomethingWithSocket(workerSocket);
}