我不喜歡這樣寫道:
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'。 –