2012-06-29 38 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

其实服务没有什么特别的线程......至少我已经将一个复杂的多线程桌面程序转换为一次服务,并且根本没有任何问题。 –

相关问题