C# TcpListener 监听自动停止(急急急)
自写的 Socket 监听程序,放到外网服务器上面后,监听一段时间(特别是人多的时候),会出现监听不到数据的情况,代码如下:
listener = new TcpListener(ServerIP, iPortNum);
listener.Start();
Thread th = new Thread(new ThreadStart(ListenThreadMethod));
th.Start();
private void ListenThreadMethod()
{
while(! toDispose)
{
if(this.stateIsStop)
{
Thread.Sleep(100) ;
continue ;
}
if(! this.tcpListener.Pending())
{
Thread.Sleep(100) ;
continue ;
}
TcpClient tcp_client = this.tcpListener.AcceptTcpClient() ;
if(this.TcpConnectionEstablished != null)
{
this.TcpConnectionEstablished(tcp_client.GetStream()) ;
}
}
this.manualEventDispose.Set() ;
}
下面是this.TcpConnectionEstablished(tcp_client.GetStream())事件触发后所调用的方法
private void esfTcpListener_TcpConnectionEstablished(System.Net.Sockets.NetworkStream stream)
{
ISafeNetworkStream safeStream = new SafeNetworkStream(stream) ;
ContextKey key = new ContextKey(safeStream ,this.recieveBuffSize) ;
this.contextKeyManager.InsertContextKey(key) ;
int connectID = key.NetStream.GetHashCode() ;
if(this.SomeOneConnected != null)
{
this.SomeOneConnected(connectID) ;
}
key.NetStream.NetworkStream.BeginRead(key.Buffer ,0 ,this.contractHelper.MessageHeaderLength ,new AsyncCallback(this.ServeOverLap) ,key) ;
}
停止监听后,客户端还是可以通过下面代码与服务器建立连接
TcpClient client = new TcpClient();
IPAddress[] ipaddr = Dns.GetHostAddresses(this.serverIP);
client.Connect(ipaddr[0], this.port);
NetworkStream stream = client.GetStream();
但是服务器端的key.NetStream.NetworkStream.BeginRead一直获取不到数据。
是不是BeginRead这个有异常没有处理,还是防火墙或者机器设置的问题或者机房硬件防火墙的问题呢?
希望各位大侠帮忙啊!!!!!