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

上传人:仙*** 文档编号:33166833 上传时间:2021-10-16 格式:DOC 页数:8 大小:32.85KB
收藏 版权申诉 举报 下载
如何处理服务器或客户端socket断开_第1页
第1页 / 共8页
如何处理服务器或客户端socket断开_第2页
第2页 / 共8页
如何处理服务器或客户端socket断开_第3页
第3页 / 共8页
资源描述:

《如何处理服务器或客户端socket断开》由会员分享,可在线阅读,更多相关《如何处理服务器或客户端socket断开(8页珍藏版)》请在装配图网上搜索。

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的返回

展开阅读全文
温馨提示:
1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
2: 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
3.本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
关于我们 - 网站声明 - 网站地图 - 资源地图 - 友情链接 - 网站客服 - 联系我们

copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!