C#使用Socket實現(xiàn)心跳的方法示例
更新時間:2020年02月12日 11:42:13 作者:風之_訴
這篇文章主要介紹了C#使用Socket實現(xiàn)心跳的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
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); //到達時間的時候執(zhí)行事件; 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("連接數(shù):" + 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() + "]連接關(guān)閉..."); break; } data += Encoding.UTF8.GetString(bytes, 0, bytesRec); ReceiveText("收到消息:" + data); string sendStr = "服務端已經(jīng)收到信息!"; 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); //創(chuàng)建一個Socket類 Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Bind(ipend);//綁定2000端口 s.Listen(0);//開始監(jiān)聽 ReceiveText("啟動Socket監(jiān)聽..."); while (true) { Socket connectionSocket = s.Accept();//為新建連接創(chuàng)建新的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和端口轉(zhuǎn)化為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, SocketType.Stream, ProtocolType.Tcp);//創(chuàng)建一個Socket try { c.Connect(ipend);//連接到服務器 Console.WriteLine("連接到Socket服務端..."); Console.WriteLine("發(fā)送消息到服務端..."); string sendStr = "m s g"; byte[] bs = Encoding.UTF8.GetBytes(sendStr); c.Send(bs, bs.Length, 0); string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = c.Receive(recvBytes, recvBytes.Length, 0);//從服務器端接受返回信息 recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes); Console.WriteLine("服務器返回信息:" + recvStr); } catch (ArgumentNullException ex1) { Console.WriteLine("ArgumentNullException:{0}", ex1); } catch (SocketException ex2) { Console.WriteLine("SocketException:{0}", ex2); } Console.ReadKey(); } }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#框架winform實現(xiàn)簡單點餐系統(tǒng)
這篇文章主要為大家詳細介紹了C#框架winform實現(xiàn)簡單點餐系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07C#中一個方法返回多個值的實現(xiàn)方法小結(jié)
通常一個方法只能返回一個值,但是如果在某些時候,我們想要返回多個值,例如某個方法將一個浮點數(shù)分割成一個整數(shù)和一個小數(shù)返回,因此本文給大家介紹了C#中一個方法返回多個值的實現(xiàn)方法及示例代碼,需要的朋友可以參考下2024-05-05C#手動操作DataGridView使用各種數(shù)據(jù)源填充表格實例
本文主要介紹了C#手動操作DataGridView使用各種數(shù)據(jù)源填充表格實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02C#使用泛型隊列Queue實現(xiàn)生產(chǎn)消費模式
這篇文章介紹了C#使用泛型隊列Queue實現(xiàn)生產(chǎn)消費模式的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-10-10C#開發(fā)Windows服務實例之實現(xiàn)禁止QQ運行
這篇文章主要介紹了通過C#開發(fā)Windows服務,查殺qq進程的服務功能,需要的朋友可以參考下2013-10-10