【发布时间】:2012-06-30 20:43:05
【问题描述】:
我有一个在套接字上监听的服务器。此服务器是 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 事件日志中看到任何异常或错误详细信息?
标签: c# multithreading sockets tcpclient