国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

C#中怎么利用Socket實(shí)現心跳

發(fā)布時(shí)間:2021-07-27 11:45 來(lái)源:億速云 閱讀:0 作者:Leah 欄目: 編程語(yǔ)言 歡迎投稿:712375056

本篇文章給大家分享的是有關(guān)C#中怎么利用Socket實(shí)現心跳,小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習,希望大家閱讀完這篇文章后可以有所收獲,話(huà)不多說(shuō),跟著(zhù)小編一起來(lái)看看吧。

Server端代碼:

class Program{  static SocketListener listener;   public static void Main(string[] args)  {    //實(shí)例化Timer類(lèi),設置間隔時(shí)間為5000毫秒;    System.Timers.Timer t = new System.Timers.Timer(5000);    t.Elapsed += new System.Timers.ElapsedEventHandler(CheckListen);    //到達時(shí)間的時(shí)候執行事件;     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("客戶(hù)端[" + _connection.RemoteEndPoint.ToString() + "]連接關(guān)閉...");          break;        }         data += Encoding.UTF8.GetString(bytes, 0, bytesRec);        ReceiveText("收到消息:" + data);         string sendStr = "服務(wù)端已經(jīng)收到信息!";        byte[] bs = Encoding.UTF8.GetBytes(sendStr);        _connection.Send(bs, bs.Length, 0);      }    }    catch (Exception)    {      ReceiveText("客戶(hù)端[" + _connection.RemoteEndPoint.ToString() + "]連接已斷開(kāi)...");      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..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 )建一個(gè)Socket類(lèi)      Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);      s.Bind(ipend);//綁定2000端口      s.Listen(0);//開(kāi)始監聽(tīng)       ReceiveText("啟動(dòng)Socket監聽(tīng)...");       while (true)      {        Socket connectionSocket = s.Accept();//為新建連接創(chuàng )建新的Socket         ReceiveText("客戶(hù)端[" + connectionSocket.RemoteEndPoint.ToString() + "]連接已建立...");         Connection gpsCn = new Connection(connectionSocket);        gpsCn.ReceiveTextEvent += new Connection.ReceiveTextHandler(ReceiveText);         Connection.Add(connectionSocket.RemoteEndPoint.ToString(), gpsCn);         //在新線(xiàn)程中啟動(dòng)新的socket連接,每個(gè)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實(shí)例    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 )建一個(gè)Socket     try    {      c.Connect(ipend);//連接到       Console.WriteLine("連接到Socket服務(wù)端...");       Console.WriteLine("發(fā)送消息到服務(wù)端...");      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);//從服務(wù)器端接受返回信息      recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);       Console.WriteLine("服務(wù)器返回信息:" + recvStr);    }    catch (ArgumentNullException ex1)    {      Console.WriteLine("ArgumentNullException:{0}", ex1);    }    catch (SocketException ex2)    {      Console.WriteLine("SocketException:{0}", ex2);    }     Console.ReadKey();  }}

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。

噜噜色.com| 亚洲AV日韩AV无码| 色综合无码AV网站| 精品一区二区三区东京热| 国产精品XXX在线| 西西人体大胆午夜啪啪|