C#使用Socket實現心跳的方法示例
阿新 • • 發佈:2020-02-13
Server端程式碼:
class Program { static SocketListener listener; public static void Main(string[] args) { //例項化Timer類,設定間隔時間為5000毫秒; System.Timers.Timer t = new System.Timers.Timer(5000); t.Elapsed += new System.Timers.ElapsedEventHandler(CheckListen); //到達時間的時候執行事件; t.AutoReset = true; t.Start(); listener = new SocketListener(); listener.ReceiveTextEvent += new SocketListener.ReceiveTextHandler(ShowText); listener.StartListen(); Console.ReadKey(); } private static void ShowText(string text) { Console.WriteLine(text); } private static void CheckListen(object sender,System.Timers.ElapsedEventArgs e) { if (listener != null && listener.Connection != null) { Console.WriteLine("連線數:" + listener.Connection.Count.ToString()); } } } public class Connection { Socket _connection; public Connection(Socket socket) { _connection = socket; } public void WaitForSendData(object connection) { try { while (true) { byte[] bytes = new byte[1024]; string data = ""; //等待接收訊息 int bytesRec = this._connection.Receive(bytes); if (bytesRec == 0) { // ReceiveText("客戶端[" + _connection.RemoteEndPoint.ToString() + "]連線關閉..."); break; } data += Encoding.UTF8.GetString(bytes,bytesRec); ReceiveText("收到訊息:" + data); string sendStr = "服務端已經收到資訊!"; byte[] bs = Encoding.UTF8.GetBytes(sendStr); _connection.Send(bs,bs.Length,0); } } catch (Exception) { ReceiveText("客戶端[" + _connection.RemoteEndPoint.ToString() + "]連線已斷開..."); Hashtable hConnection = connection as Hashtable; if (hConnection.Contains(_connection.RemoteEndPoint.ToString())) { hConnection.Remove(_connection.RemoteEndPoint.ToString()); } } } public delegate void ReceiveTextHandler(string text); public event ReceiveTextHandler ReceiveTextEvent; private void ReceiveText(string text) { if (ReceiveTextEvent != null) { ReceiveTextEvent(text); } } } public class SocketListener { public Hashtable Connection = new Hashtable(); public void StartListen() { Agine: try { //埠號、IP地址 //int port = 8889; //string host = "127.0.0.1"; //IPAddress ip = IPAddress.Parse(host); //IPEndPoint ipe = new IPEndPoint(ip,port); string ip = string.Empty; System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()); for (int i = 0; i != IpEntry.AddressList.Length; i++) { if (!IpEntry.AddressList[i].IsIPv6LinkLocal) { ip = IpEntry.AddressList[i].ToString(); } } IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(ip),6000); //建立一個Socket類 Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); s.Bind(ipend);//繫結2000埠 s.Listen(0);//開始監聽 ReceiveText("啟動Socket監聽..."); while (true) { Socket connectionSocket = s.Accept();//為新建連線建立新的Socket ReceiveText("客戶端[" + connectionSocket.RemoteEndPoint.ToString() + "]連線已建立..."); Connection gpsCn = new Connection(connectionSocket); gpsCn.ReceiveTextEvent += new Connection.ReceiveTextHandler(ReceiveText); Connection.Add(connectionSocket.RemoteEndPoint.ToString(),gpsCn); //在新執行緒中啟動新的socket連線,每個socket等待,並保持連線 Thread thread = new Thread(gpsCn.WaitForSendData); thread.Name = connectionSocket.RemoteEndPoint.ToString(); thread.Start(Connection); } } catch (ArgumentNullException ex1) { ReceiveText("ArgumentNullException:" + ex1); } catch (SocketException ex2) { ReceiveText("SocketException:" + ex2); } goto Agine; } public delegate void ReceiveTextHandler(string text); public event ReceiveTextHandler ReceiveTextEvent; private void ReceiveText(string text) { if (ReceiveTextEvent != null) { ReceiveTextEvent(text); } } }
Client端程式碼:
class Program { static void Main(string[] args) { Socket c; //int port = 4029; // 避免使用127.0.0.1,我在本機測試是不能執行的 //string host = "127.0.0.1"; //IPAddress ip = IPAddress.Parse(host); //IPEndPoint ipe = new IPEndPoint(ip,port);//把ip和埠轉化為IPEndPoint例項 string ip = string.Empty; System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()); for (int i = 0; i != IpEntry.AddressList.Length; i++) { if (!IpEntry.AddressList[i].IsIPv6LinkLocal) { ip = IpEntry.AddressList[i].ToString(); } } IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(ip),6000); c = new Socket(AddressFamily.InterNetwork,ProtocolType.Tcp);//建立一個Socket try { c.Connect(ipend);//連線到伺服器 Console.WriteLine("連線到Socket服務端..."); Console.WriteLine("傳送訊息到服務端..."); string sendStr = "m s g"; byte[] bs = Encoding.UTF8.GetBytes(sendStr); c.Send(bs,0); string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = c.Receive(recvBytes,recvBytes.Length,0);//從伺服器端接受返回資訊 recvStr += Encoding.UTF8.GetString(recvBytes,bytes); Console.WriteLine("伺服器返回資訊:" + recvStr); } catch (ArgumentNullException ex1) { Console.WriteLine("ArgumentNullException:{0}",ex1); } catch (SocketException ex2) { Console.WriteLine("SocketException:{0}",ex2); } Console.ReadKey(); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。