如何处理服务器或客户端socket断开.doc

上传人:文库蛋蛋多 文档编号:2385361 上传时间:2023-02-17 格式:DOC 页数:10 大小:24KB
返回 下载 相关 举报
如何处理服务器或客户端socket断开.doc_第1页
第1页 / 共10页
如何处理服务器或客户端socket断开.doc_第2页
第2页 / 共10页
如何处理服务器或客户端socket断开.doc_第3页
第3页 / 共10页
如何处理服务器或客户端socket断开.doc_第4页
第4页 / 共10页
如何处理服务器或客户端socket断开.doc_第5页
第5页 / 共10页
点击查看更多>>
资源描述

《如何处理服务器或客户端socket断开.doc》由会员分享,可在线阅读,更多相关《如何处理服务器或客户端socket断开.doc(10页珍藏版)》请在三一办公上搜索。

1、编程经验谈 如何处理socket连接后服务器端或Socket编程经验谈-如何处理socket连接后服务器端或客户端的断开(转)2010年12月29日星期三14:50现象:服务器端等待客户断连接,当socket连接建立后,如果客户端异常断开,服务器会抛出异常,从而导致程序运行中断目标:希望服务器一直等待连接,客户端中断后程序不退出,而客户端重新恢复后可以继续保持连接代码:public class Receivepublic static byte buffer=new byte1024;public static ManualResetEvent socketEvent=new ManualRe

2、setEvent(false);public static Socket sListener=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);public static Socket handler=null;public static string ClientBroken=An connection was forcibly closed by the remote host;public static void receive()tryConsole.WriteLine(Main Thre

3、adID:+AppDomain.GetCurrentThreadId();byte bytes=new byte1024;IPAddress ipAddr=IPAddress.Parse(127.0.0.1);int Port=10001;IPEndPoint EPServer=new IPEndPoint(ipAddr,Port);/Binding asocket sListener.Bind(EPServer);/Start listening sListener.Listen(10);while(true)if(handler=null)/first must make aconnect

4、 Console.WriteLine(waiting for aconnection.);/asychronous function for accepting connections sListener.BeginAccept(new AsyncCallback(AcceptCallback),sListener);socketEvent.WaitOne();handler.BeginReceive(buffer,0,buffer.Length,0,new AsyncCallback(ReceiveCallback),handler);socketEvent.WaitOne();elseCo

5、nsole.WriteLine(waiting next message.);socketEvent.Reset();handler.BeginReceive(buffer,0,buffer.Length,0,new AsyncCallback(ReceiveCallback),handler);socketEvent.WaitOne();Console.ReadLine();catch(Exception e)Console.WriteLine(e.ToString();Console.ReadLine();public static void AcceptCallback(IAsyncRe

6、sult ar)tryConsole.WriteLine(AcceptCallback Thread ID:+AppDomain.GetCurrentThreadId();Socket listener=(Socket)ar.AsyncState;/new socket handler=listener.EndAccept(ar);handler.BeginReceive(buffer,0,buffer.Length,0,new AsyncCallback(ReceiveCallback),handler);catch(Exception e)Console.WriteLine(e.ToStr

7、ing();public static void ReceiveCallback(IAsyncResult ar)string err_message=null;tryConsole.WriteLine(ReceiveCallback Thread ID:+AppDomain.GetCurrentThreadId();string content=String.Empty;handler=(Socket)ar.AsyncState;int bytesRead=handler.EndReceive(ar);/if there is some data.if(bytesRead 0)/append

8、 it to the main string content+=Encoding.ASCII.GetString(buffer,0,bytesRead);/if we encounter the end of message character if(content.IndexOf(char)3)-1|content.IndexOf(char)16)-1)Console.WriteLine(Read+content.Length+bytes from socket.n Data:+content);socketEvent.Set();else/otherwise receive the rem

9、aining data handler.BeginReceive(buffer,0,buffer.Length,0,new AsyncCallback(ReceiveCallback),handler);catch(Exception e)err_message=e.Message;if(err_message.IndexOf(An existing connection was forcibly closed by the remote host)-1)Console.WriteLine(An existing connection was forcibly closed by the re

10、mote host);/handler.Shutdown(SocketShutdown.Both);/handler.Close();Console.WriteLine(waiting for aconnection.);/asychronous function for accepting connections sListener.BeginAccept(new AsyncCallback(AcceptCallback),sListener);elseConsole.WriteLine(e.ToString();说明:关键在于最后这段的异常处理,接收中断后,服务器端重新等待接收。现象:客户

11、端与服务器连接,当socket连接建立后,如果服务器端异常断开,客户端会抛出异常,从而导致程序运行中断目标:希望客户端出现提示,服务器端中断后程序不退出,而服务器端重新恢复后可以继续保持连接代码:public class AsyncCommpublic static string theResponse=;public static byte buffer=new byte1024;public static ManualResetEvent socketEvent=new ManualResetEvent(false);public static Socket sClient=new Soc

12、ket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);public static IPEndPoint EPServer=new IPEndPoint(IPAddress.Parse(127.0.0.1),10001);public static void send(string data)byte byteData=null;byteData=Encoding.ASCII.GetBytes(data);tryif(!sClient.Connected)Console.WriteLine(System.DateTi

13、me.Now.ToString(yyyy-MM-dd HH:mm:ss:ffff)+Connect begining.);sClient.BeginConnect(EPServer,new AsyncCallback(ConnectCallback),sClient);socketEvent.WaitOne();sClient.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),sClient);socketEvent.WaitOne();catch(Exception e)Console.WriteLi

14、ne(Server side is broken.);socketEvent.Reset();return;public static void ConnectCallback(IAsyncResult ar)tryThread thr=Thread.CurrentThread;Console.WriteLine(ConnectCallback Thread State:+AppDomain.GetCurrentThreadId();Socket sClient=(Socket)ar.AsyncState;sClient.EndConnect(ar);Console.WriteLine(Soc

15、ket connected to+sClient.RemoteEndPoint.ToString();socketEvent.Set();catch(Exception ex)Console.WriteLine(System.DateTime.Now.ToString(yyyy-MM-dd HH:mm:ss:ffff)+|+AppDomain.GetCurrentThreadId()+|3-Level 3Server connection is broken,waiting for Level 3Server connection.);sClient=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);socketEvent.Set();receive函数相同,可以参照写出说明:在每次发送或接收时检测当前socket是否连接,如果没有连接,就启动连接,并阻塞线程等待ConnectCallback的返回

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 建筑/施工/环境 > 项目建议


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号