我有一个服务器的套接字上收听。该服务器是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