资源描述:
《如何处理服务器或客户端socket断开》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、编程经验谈如何处理socket连接后服务器端或Socket编程经验谈---如何处理socket连接后服务器端或客户端的断开(转)2010年12月29日星期三14:50现象:服务器端等待客户断连接,当socket连接建立后,如果客户端异常断开,服务器会抛出异常,从而导致程序运行中断目标:希望服务器一直等待连接,客户端中断后程序不退出,而客户端重新恢复后可以继续保持连接代码:publicclassReceive{publicstaticbytebuffer=newbyte[1024];publicstaticManualResetEventsocketEvent=newManualResetE
2、vent(false);publicstaticSocketsListener=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);publicstaticSockethandler=null;publicstaticstringClientBroken="Anconnectionwasforciblyclosedbytheremotehost";publicstaticvoidreceive(){try{Console.WriteLine("MainThreadID:"+AppDomain.Ge
3、tCurrentThreadId());bytebytes=newbyte[1024];IPAddressipAddr=IPAddress.Parse("127.0.0.1");intPort=10001;IPEndPointEPServer=newIPEndPoint(ipAddr,Port);//BindingasocketsListener.Bind(EPServer);//StartlisteningsListener.Listen(10);while(true){if(handler==null){//firstmustmakeaconnectConsole.WriteLine(
4、"waitingforaconnection.");//asychronousfunctionforacceptingconnectionssListener.BeginAccept(newAsyncCallback(AcceptCallback),sListener);socketEvent.WaitOne();handler.BeginReceive(buffer,0,buffer.Length,0,newAsyncCallback(ReceiveCallback),handler);socketEvent.WaitOne();}else{Console.WriteLine("wait
5、ingnextmessage.");socketEvent.Reset();handler.BeginReceive(buffer,0,buffer.Length,0,newAsyncCallback(ReceiveCallback),handler);socketEvent.WaitOne();}}Console.ReadLine();}catch(Exceptione){Console.WriteLine(e.ToString());}Console.ReadLine();}publicstaticvoidAcceptCallback(IAsyncResultar){try{Conso
6、le.WriteLine("AcceptCallbackThreadID:"+AppDomain.GetCurrentThreadId());Socketlistener=(Socket)ar.AsyncState;//newsockethandler=listener.EndAccept(ar);handler.BeginReceive(buffer,0,buffer.Length,0,newAsyncCallback(ReceiveCallback),handler);}catch(Exceptione){Console.WriteLine(e.ToString());}}public
7、staticvoidReceiveCallback(IAsyncResultar){stringerr_message=null;try{Console.WriteLine("ReceiveCallbackThreadID:"+AppDomain.GetCurrentThreadId());stringcontent=String.Empty;handler=(Socket)ar.AsyncState;intbytesR