C#使用Socket实现心跳的方法示例

2020-02-12 14:02:51王振洲

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, SocketType.Stream, 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, 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();
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。