我不喜欢这样写道:
void Loop()
{
TcpListener l = new TcpListener(IPAddress.Any, Port);
WaitHandle[] h = new WaitHandle[2];
h[0] = StopEvent;
WriteInfo("Listening on port {0}", Port);
l.Start();
while (true)
{
var r = l.BeginAcceptTcpClient(null, null);
h[1] = r.AsyncWaitHandle;
// Wait for next client to connect or StopEvent
int w = WaitHandle.WaitAny(h);
if (w == 0) // StopEvent was set (from outside), terminate loop
break;
if (w == 1)
{
TcpClient c = l.EndAcceptTcpClient(r);
c.ReceiveTimeout = 90000;
c.SendTimeout = 90000;
// client is connected, spawn thread for it and continue to wait for others
var t = new Thread(ServeClient);
t.IsBackground = true;
t.Start(c);
}
}
l.Stop();
WriteInfo("Listener stopped");
}
其中Loop
某处开始这样的:
StopEvent = new ManualResetEvent(false);
LoopThread = new Thread(Loop);
LoopThread.Start();
StopEvent
用于终止听力循环。 ServeClient
作为名称表示连接的客户端,看起来像这样:
void ServeClient(object State)
{
TcpClient c = (TcpClient)State;
NetworkStream s = c.GetStream();
try
{
// Communicate with your client
}
finally
{
s.Close();
c.Close();
}
}
这部作品在任何.NET应用程序(Windows服务,控制台,WPF或WinForms的)
一个建议是使用'BeginReceive'和[Socket](http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx)类上的'EndReceive'。然后在回调处理程序中再次调用'BeginReceive'。 –