C#使用Socket实现心跳的方法示例
Server端代码:
classProgram { staticSocketListenerlistener; publicstaticvoidMain(string[]args) { //实例化Timer类,设置间隔时间为5000毫秒; System.Timers.Timert=newSystem.Timers.Timer(5000); t.Elapsed+=newSystem.Timers.ElapsedEventHandler(CheckListen); //到达时间的时候执行事件; t.AutoReset=true; t.Start(); listener=newSocketListener(); listener.ReceiveTextEvent+=newSocketListener.ReceiveTextHandler(ShowText); listener.StartListen(); Console.ReadKey(); } privatestaticvoidShowText(stringtext) { Console.WriteLine(text); } privatestaticvoidCheckListen(objectsender,System.Timers.ElapsedEventArgse) { if(listener!=null&&listener.Connection!=null) { Console.WriteLine("连接数:"+listener.Connection.Count.ToString()); } } } publicclassConnection { Socket_connection; publicConnection(Socketsocket) { _connection=socket; } publicvoidWaitForSendData(objectconnection) { try { while(true) { byte[]bytes=newbyte[1024]; stringdata=""; //等待接收消息 intbytesRec=this._connection.Receive(bytes); if(bytesRec==0) { //ReceiveText("客户端["+_connection.RemoteEndPoint.ToString()+"]连接关闭..."); break; } data+=Encoding.UTF8.GetString(bytes,0,bytesRec); ReceiveText("收到消息:"+data); stringsendStr="服务端已经收到信息!"; byte[]bs=Encoding.UTF8.GetBytes(sendStr); _connection.Send(bs,bs.Length,0); } } catch(Exception) { ReceiveText("客户端["+_connection.RemoteEndPoint.ToString()+"]连接已断开..."); HashtablehConnection=connectionasHashtable; if(hConnection.Contains(_connection.RemoteEndPoint.ToString())) { hConnection.Remove(_connection.RemoteEndPoint.ToString()); } } } publicdelegatevoidReceiveTextHandler(stringtext); publiceventReceiveTextHandlerReceiveTextEvent; privatevoidReceiveText(stringtext) { if(ReceiveTextEvent!=null) { ReceiveTextEvent(text); } } } publicclassSocketListener { publicHashtableConnection=newHashtable(); publicvoidStartListen() { Agine: try { //端口号、IP地址 //intport=8889; //stringhost="127.0.0.1"; //IPAddressip=IPAddress.Parse(host); //IPEndPointipe=newIPEndPoint(ip,port); stringip=string.Empty; System.Net.IPHostEntryIpEntry=System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()); for(inti=0;i!=IpEntry.AddressList.Length;i++) { if(!IpEntry.AddressList[i].IsIPv6LinkLocal) { ip=IpEntry.AddressList[i].ToString(); } } IPEndPointipend=newIPEndPoint(IPAddress.Parse(ip),6000); //创建一个Socket类 Sockets=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); s.Bind(ipend);//绑定2000端口 s.Listen(0);//开始监听 ReceiveText("启动Socket监听..."); while(true) { SocketconnectionSocket=s.Accept();//为新建连接创建新的Socket ReceiveText("客户端["+connectionSocket.RemoteEndPoint.ToString()+"]连接已建立..."); ConnectiongpsCn=newConnection(connectionSocket); gpsCn.ReceiveTextEvent+=newConnection.ReceiveTextHandler(ReceiveText); Connection.Add(connectionSocket.RemoteEndPoint.ToString(),gpsCn); //在新线程中启动新的socket连接,每个socket等待,并保持连接 Threadthread=newThread(gpsCn.WaitForSendData); thread.Name=connectionSocket.RemoteEndPoint.ToString(); thread.Start(Connection); } } catch(ArgumentNullExceptionex1) { ReceiveText("ArgumentNullException:"+ex1); } catch(SocketExceptionex2) { ReceiveText("SocketException:"+ex2); } gotoAgine; } publicdelegatevoidReceiveTextHandler(stringtext); publiceventReceiveTextHandlerReceiveTextEvent; privatevoidReceiveText(stringtext) { if(ReceiveTextEvent!=null) { ReceiveTextEvent(text); } } }
Client端代码:
classProgram { staticvoidMain(string[]args) { Socketc; //intport=4029; //避免使用127.0.0.1,我在本机测试是不能运行的 //stringhost="127.0.0.1"; //IPAddressip=IPAddress.Parse(host); //IPEndPointipe=newIPEndPoint(ip,port);//把ip和端口转化为IPEndPoint实例 stringip=string.Empty; System.Net.IPHostEntryIpEntry=System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()); for(inti=0;i!=IpEntry.AddressList.Length;i++) { if(!IpEntry.AddressList[i].IsIPv6LinkLocal) { ip=IpEntry.AddressList[i].ToString(); } } IPEndPointipend=newIPEndPoint(IPAddress.Parse(ip),6000); c=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);//创建一个Socket try { c.Connect(ipend);//连接到服务器 Console.WriteLine("连接到Socket服务端..."); Console.WriteLine("发送消息到服务端..."); stringsendStr="msg"; byte[]bs=Encoding.UTF8.GetBytes(sendStr); c.Send(bs,bs.Length,0); stringrecvStr=""; byte[]recvBytes=newbyte[1024]; intbytes; bytes=c.Receive(recvBytes,recvBytes.Length,0);//从服务器端接受返回信息 recvStr+=Encoding.UTF8.GetString(recvBytes,0,bytes); Console.WriteLine("服务器返回信息:"+recvStr); } catch(ArgumentNullExceptionex1) { Console.WriteLine("ArgumentNullException:{0}",ex1); } catch(SocketExceptionex2) { Console.WriteLine("SocketException:{0}",ex2); } Console.ReadKey(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。