我有一個服務器的套接字上收聽。該服務器是Windows服務。Windows服務關閉時我斷開一個客戶端套接字
我的問題是:當我斷開客戶socket.Disconnect(false);
服務,以便封閉和其他客戶強行平倉或新連接拒絕。我認爲,當服務殺死這個客戶端線程時,服務不會回到主線程。
粘貼用於服務(服務器功能),我的代碼。線程管理是否正確?
我運行
this.tcpListener = new TcpListener(ipEnd);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
對不起我的英文不好,並感謝服務器任何建議
服務進程退出?您是否在調試器/ Windows事件日誌中看到任何異常或錯誤細節? – Jan