zoukankan      html  css  js  c++  java
  • .net 调度器怎么实现心跳(socket除了他,没选择吧)

    自己写调度器,就要从tcp通信入手;心跳的实现除了使用socket,想不到其他任何方案。

    socket基本使用demo:

    • Socket Client:
     1  static void Main(string[] args)
     2         {
     3             Socket c;
     4 
     5             //int port = 4029;
     6             // 避免使用127.0.0.1,我在本机测试是不能运行的
     7             //string host = "127.0.0.1";
     8             //IPAddress ip = IPAddress.Parse(host);
     9             //IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
    10             string ip = string.Empty;
    11             System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
    12             for (int i = 0; i != IpEntry.AddressList.Length; i++)
    13             {
    14                 if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
    15                 {
    16                     ip = IpEntry.AddressList[i].ToString();
    17                 }
    18             }
    19             IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(ip), 8889);
    20 
    21             c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
    22 
    23             try
    24             {
    25                 c.Connect(ipend);//连接到服务器
    26 
    27                 Console.WriteLine("连接到Socket服务端...");
    28 
    29                 Console.WriteLine("发送消息到服务端...");
    30                 string sendStr = "m s g";
    31                 byte[] bs = Encoding.Default.GetBytes(sendStr);
    32                 c.Send(bs, bs.Length, 0);
    33 
    34                 string recvStr = "";
    35                 byte[] recvBytes = new byte[1024];
    36                 int bytes;
    37                 bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
    38                 recvStr += Encoding.Default.GetString(recvBytes, 0, bytes);
    39 
    40                 Console.WriteLine("服务器返回信息:" + recvStr);
    41             }
    42             catch (ArgumentNullException ex1)
    43             {
    44                 Console.WriteLine("ArgumentNullException:{0}", ex1);
    45             }
    46             catch (SocketException ex2)
    47             {
    48                 Console.WriteLine("SocketException:{0}", ex2);
    49             }
    50             //string ip = string.Empty;
    51             //System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
    52             //for (int i = 0; i != IpEntry.AddressList.Length; i++)
    53             //{
    54             //    if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
    55             //    {
    56             //        ip = IpEntry.AddressList[i].ToString();
    57             //    }
    58             //}
    59             //IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(ip), 8889);
    60             //Socket sc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    61             //sc.Connect(ipend);
    62             //string message = "请升级软件";
    63             //byte[] bt = Encoding.GetEncoding("gb2312").GetBytes(message);
    64             //sc.Send(bt, bt.Length, 0);
    65             //byte[] rebuff = new byte[1024];
    66             //int recive = sc.Receive(rebuff, rebuff.Length, 0);
    67             //string returnval = "";
    68             //returnval += Encoding.GetEncoding("gb2312").GetString(rebuff, 0, recive); sc.Close();
    69             //Console.WriteLine(returnval);
    70 
    71 
    72             Console.ReadKey();
    73         }
    • Socket Server:
      1  class Program
      2     {
      3         static SocketListener listener;
      4 
      5         public static void Main(string[] args)
      6         {
      7             System.Timers.Timer t = new System.Timers.Timer(2000);
      8             //实例化Timer类,设置间隔时间为5000毫秒;
      9             t.Elapsed += new System.Timers.ElapsedEventHandler(CheckListen);
     10             //到达时间的时候执行事件; 
     11             t.AutoReset = true;
     12             t.Start();
     13 
     14             listener = new SocketListener();
     15             listener.ReceiveTextEvent += new SocketListener.ReceiveTextHandler(ShowText);
     16             listener.StartListen();
     17 
     18             //    客户最近提出一个需求,要在WEB上远程管理客户端软件。那我们就仿路由器那种模式用SOCKET来解决吧。做了个DEMO,本机测试OK,拿到别的机器上做服务器,
     19             //提示由于目标机器积极拒绝,无法连接。查询各种资料,有的说是端口没开,有的说是服务没开。各种雾水啊!仔细一想,问题可能出在本机在局域网IP上,
     20             //而不是用127.0.0.1。更正代码后,问题解决。下面演示服务器端代码的关键部分。   
     21             //string ip = "";
     22             //System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
     23             //for (int i = 0; i != IpEntry.AddressList.Length; i++)
     24             //{
     25             //    if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
     26             //    {
     27             //        ip = IpEntry.AddressList[i].ToString();
     28             //    }
     29             //}
     30 
     31             //IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(ip), 8889);
     32             //Socket sc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     33             //sc.Bind(ipend);
     34 
     35             //Socket acc;
     36 
     37             //while (true)
     38             //{
     39             //    sc.Listen(1);
     40             //    acc = sc.Accept();
     41             //    byte[] buff = new byte[1024];
     42             //    int recbyte = acc.Receive(buff, buff.Length, 0);
     43             //    if (recbyte == 0)
     44             //        break;
     45             //    string reciveval = "";
     46             //    reciveval += Encoding.Default.GetString(buff, 0, recbyte);
     47 
     48             //    Console.WriteLine(reciveval);
     49             //    string returnValue = "Accepted";
     50             //    byte[] returnBy = Encoding.Default.GetBytes(returnValue);
     51             //    acc.Send(returnBy, returnBy.Length, 0);
     52             //}
     53 
     54             //acc.Close();
     55             //sc.Close();
     56 
     57 
     58 
     59             Console.ReadKey();
     60         }
     61 
     62         private static void ShowText(string text)
     63         {
     64             Console.WriteLine(text);
     65         }
     66 
     67         private static void CheckListen(object sender, System.Timers.ElapsedEventArgs e)
     68         {
     69             if (listener != null && listener.Connection != null)
     70             {
     71                 Console.WriteLine("连接数:" + listener.Connection.Count.ToString());
     72             }
     73         }
     74     }
     75 
     76     public class Connection
     77     {
     78         Socket _connection;
     79 
     80         public Connection(Socket socket)
     81         {
     82             _connection = socket;
     83         }
     84 
     85         public void WaitForSendData()
     86         {
     87             try
     88             {
     89                 while (true)
     90                 {
     91                     byte[] bytes = new byte[1024];
     92                     string data = "";
     93 
     94                     //等待接收消息
     95                     int bytesRec = this._connection.Receive(bytes);
     96 
     97                     if (bytesRec == 0)
     98                     {
     99                         // ReceiveText("客户端[" + _connection.RemoteEndPoint.ToString() + "]连接关闭...");
    100                         break;
    101                     }
    102 
    103                     data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
    104                     ReceiveText("收到消息:" + data);
    105 
    106                     string sendStr = "服务端已经收到信息!";
    107                     byte[] bs = Encoding.UTF8.GetBytes(sendStr);
    108                     _connection.Send(bs, bs.Length, 0);
    109                 }
    110             }
    111             catch (Exception ex)
    112             {
    113                 Console.WriteLine(ex.Message);
    114             }
    115         }
    116 
    117         public delegate void ReceiveTextHandler(string text);
    118         public event ReceiveTextHandler ReceiveTextEvent;
    119         private void ReceiveText(string text)
    120         {
    121             if (ReceiveTextEvent != null)
    122             {
    123                 ReceiveTextEvent(text);
    124             }
    125         }
    126     }
    127 
    128     public class SocketListener
    129     {
    130         public Hashtable Connection = new Hashtable();
    131 
    132         public void StartListen()
    133         {
    134         Agine:
    135             try
    136             {
    137                 //端口号、IP地址
    138                 //int port = 8889;
    139                 //string host = "127.0.0.1";
    140                 //IPAddress ip = IPAddress.Parse(host);
    141                 //IPEndPoint ipe = new IPEndPoint(ip, port);
    142                 string ip = string.Empty;
    143                 System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
    144                 for (int i = 0; i != IpEntry.AddressList.Length; i++)
    145                 {
    146                     if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
    147                     {
    148                         ip = IpEntry.AddressList[i].ToString();
    149                     }
    150                 }
    151                 IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(ip), 8889);
    152                 //创建一个Socket类
    153                 Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    154                 s.Bind(ipend);//绑定2000端口
    155                 s.Listen(0);//开始监听
    156 
    157                 ReceiveText("启动Socket监听...");
    158 
    159                 while (true)
    160                 {
    161                     Socket connectionSocket = s.Accept();//为新建连接创建新的Socket
    162 
    163                     ReceiveText("客户端[" + connectionSocket.RemoteEndPoint.ToString() + "]连接已建立...");
    164 
    165                     Connection gpsCn = new Connection(connectionSocket);
    166                     gpsCn.ReceiveTextEvent += new Connection.ReceiveTextHandler(ReceiveText);
    167 
    168                     Connection.Add(connectionSocket.RemoteEndPoint.ToString(), gpsCn);
    169 
    170                     //在新线程中启动新的socket连接,每个socket等待,并保持连接
    171                     Thread thread = new Thread(new ThreadStart(gpsCn.WaitForSendData));
    172                     thread.Name = connectionSocket.RemoteEndPoint.ToString();
    173                     thread.Start();
    174                 }
    175             }
    176             catch (ArgumentNullException ex1)
    177             {
    178                 ReceiveText("ArgumentNullException:" + ex1);
    179             }
    180             catch (SocketException ex2)
    181             {
    182                 ReceiveText("SocketException:" + ex2);
    183             }
    184 
    185             goto Agine;
    186         }
    187 
    188         public delegate void ReceiveTextHandler(string text);
    189         public event ReceiveTextHandler ReceiveTextEvent;
    190         private void ReceiveText(string text)
    191         {
    192             if (ReceiveTextEvent != null)
    193             {
    194                 ReceiveTextEvent(text);
    195             }
    196         }
    197     }

     代码实现参考:http://blog.bossma.cn/csharp/csharp_socket_example/

                         https://msdn.microsoft.com/zh-cn/library/System.Net.Sockets.Socket(v=vs.100).aspx

  • 相关阅读:
    分页类
    验证码扭曲类
    model 概念(笔记)
    php单例模式
    php 无限极分类查找家谱树
    数组的合并
    无限极分类之查找子孙树
    android xml中的xliff属性
    android 悬浮覆盖状态栏的相关建议
    【jzoj】20190323比赛总结
  • 原文地址:https://www.cnblogs.com/yy3b2007com/p/4427387.html
Copyright © 2011-2022 走看看