2012-06-29 39 views
2

我有一個服務器的套接字上收聽。該服務器是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(); 
} 

對不起我的英文不好,並感謝服務器任何建議

+0

服務進程退出?您是否在調試器/ Windows事件日誌中看到任何異常或錯誤細節? – Jan

回答

0

您提供的代碼似乎是正確的差不多。 您的應用程序會崩潰的唯一原因是該行

NetworkStream clientStream = tcpClient.GetStream(); 

如果你看一下the documentation for GetStream(),你可以看到,它可以拋出InvalidOperationException異常如果客戶機沒有連接。因此,在客戶端連接並立即斷開的情況下,這可能是一個問題。 所以只需要用try-catch來保護這段代碼。

有時也被你可能無法得到一個明確的異常報告,但在多線程應用程序崩潰。要處理這種異常,請訂閱AppDomain.CurrentDomain.UnhandledException事件。

+0

但我的客戶端正確關閉套接字,並且分配給此客戶端的線程不會拋出任何異常。問題在於聽取其餘客戶的主線程中。主線程似乎死了。移動到新應用程序(表單)的相同代碼的服務器(服務)完美工作。我知道服務對於管理線程來說太特殊了。不是嗎? – crossmax

+0

其實服務沒有什麼特別的線程......至少我已經將一個複雜的多線程桌面程序轉換爲一次服務,並且根本沒有任何問題。 –

相關問題