SoFunction
Updated on 2025-03-07

Example of C# method to achieve heartbeat using Socket

Server side code:

class Program
{
  static SocketListener listener;
 
  public static void Main(string[] args)
  {
    //Instantiate the Timer class and set the interval to 5000 milliseconds;     t = new (5000);
     += new (CheckListen);
    //Execute the event when the time arrives;     = true;
    ();
 
    listener = new SocketListener();
     += new (ShowText);
    ();
 
    ();
  }
 
  private static void ShowText(string text)
  {
    (text);
  }
 
  private static void CheckListen(object sender,  e)
  {
    if (listener != null &&  != null)
    {
      ("Number of connections:" + ());
    }
  }
}
 
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 = "";
 
        //Waiting for receiving the message        int bytesRec = this._connection.Receive(bytes);
 
        if (bytesRec == 0)
        {
          // ReceiveText("Client[" + _connection.() + "]Connection closed...");          break;
        }
 
        data += Encoding.(bytes, 0, bytesRec);
        ReceiveText("Received the message:" + data);
 
        string sendStr = "The server has received the message!";
        byte[] bs = Encoding.(sendStr);
        _connection.Send(bs, , 0);
      }
    }
    catch (Exception)
    {
      ReceiveText("Client[" + _connection.() + "]Connection has been disconnected...");
      Hashtable hConnection = connection as Hashtable;
      if ((_connection.()))
      {
        (_connection.());
      }
    }
  }
 
  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
    {
      //Port number, IP address      //int port = 8889;
      //string host = "127.0.0.1";
      //IPAddress ip = (host);
      //IPEndPoint ipe = new IPEndPoint(ip, port);
      string ip = ;
       IpEntry = (());
      for (int i = 0; i != ; i++)
      {
        if (![i].IsIPv6LinkLocal)
        {
          ip = [i].ToString();
        }
      }
      IPEndPoint ipend = new IPEndPoint((ip), 6000);
      //Create a Socket class      Socket s = new Socket(, , );
      (ipend);//Bind port 2000      (0);//Start monitoring 
      ReceiveText("Start Socket Listening...");
 
      while (true)
      {
        Socket connectionSocket = ();//Create a new socket for a new connection 
        ReceiveText("Client[" + () + "]Connection established...");
 
        Connection gpsCn = new Connection(connectionSocket);
         += new (ReceiveText);
 
        ((), gpsCn);
 
        // Start a new socket connection in a new thread, each socket waits, and keeps the connection        Thread thread = new Thread();
         = ();
        (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 side code:

class Program
{
  static void Main(string[] args)
  {
    Socket c;
 
    //int port = 4029;
    // Avoid using 127.0.0.1, my test on the machine cannot run    //string host = "127.0.0.1";
    //IPAddress ip = (host);
    //IPEndPoint ipe = new IPEndPoint(ip, port);//Convert ip and port into IPEndPoint instance    string ip = ;
     IpEntry = (());
    for (int i = 0; i != ; i++)
    {
      if (![i].IsIPv6LinkLocal)
      {
        ip = [i].ToString();
      }
    }
    IPEndPoint ipend = new IPEndPoint((ip), 6000);
 
    c = new Socket(, , );//Create a Socket 
    try
    {
      (ipend);//Connect to the server 
      ("Connect to Socket Server...");
 
      ("Send a message to the server...");
      string sendStr = "m s g";
      byte[] bs = Encoding.(sendStr);
      (bs, , 0);
 
      string recvStr = "";
      byte[] recvBytes = new byte[1024];
      int bytes;
      bytes = (recvBytes, , 0);//Accept the return information from the server side      recvStr += Encoding.(recvBytes, 0, bytes);
 
      ("Server returns information:" + recvStr);
    }
    catch (ArgumentNullException ex1)
    {
      ("ArgumentNullException:{0}", ex1);
    }
    catch (SocketException ex2)
    {
      ("SocketException:{0}", ex2);
    }
 
    ();
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.