断开一个客户端套接字时Windows服务关闭

时间:2012-06-29 09:57:29

标签: c# multithreading sockets tcpclient

我在套接字上听了一个服务器。此服务器是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();
}

抱歉我的英文不好,感谢任何建议

1 个答案:

答案 0 :(得分:0)

您提供的代码似乎几乎是正确的。 您的应用崩溃的唯一原因是

NetworkStream clientStream = tcpClient.GetStream();

如果查看the documentation for GetStream(),您可以看到如果客户端未连接,它可能会抛出InvalidOperationException。因此,在客户端连接并立即断开连接的情况下,这可能是一个问题。 所以用try-catch来保护这段代码。

有时您可能无法获得显式异常报告,但在多线程应用程序中崩溃。要处理此类异常,请订阅AppDomain.CurrentDomain.UnhandledException事件。

相关问题