永发信息网

C#TcpListener监听自动停止(急急急)

答案:2  悬赏:50  手机版
解决时间 2021-12-21 11:48
  • 提问者网友:且恨且铭记
  • 2021-12-20 13:56
自写的 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();出现问题后原来已经和服务器端建立了连接的用户,收发数据都没问题;但是新建立的连接不能收发数据。不知道是不是是不是BeginRead这个有异常没有处理,还是防火墙或者机器设置的问题或者机房硬件防火墙的问题呢?希望各位大侠帮忙啊!!!!!
最佳答案
  • 五星知识达人网友:一把行者刀
  • 2021-12-20 15:21
加上异常处理试试吧
全部回答
  • 1楼网友:冷風如刀
  • 2021-12-20 16:10

你用的是线程sleep

换一个就好!

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯