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

所属分类: 软件编程 / C#教程 阅读数: 118
收藏 0 赞 0 分享

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);
    //到达时间的时候执行事件; 
    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("客户端[" + _connection.RemoteEndPoint.ToString() + "]连接关闭...");
          break;
        }
 
        data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
        ReceiveText("收到消息:" + data);
 
        string sendStr = "服务端已经收到信息!";
        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);
      //创建一个Socket类
      Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      s.Bind(ipend);//绑定2000端口
      s.Listen(0);//开始监听
 
      ReceiveText("启动Socket监听...");
 
      while (true)
      {
        Socket connectionSocket = s.Accept();//为新建连接创建新的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和端口转化为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();
  }
}

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

更多精彩内容其他人还在看

c#开发word批量转pdf源码分享

已经安装有Office环境,借助一些简单的代码即可实现批量Word转PDF,看下面的实例源码吧
收藏 0 赞 0 分享

c# xml API操作的小例子

这篇文章主要介绍了c# xml API操作的小例子,有需要的朋友可以参考一下
收藏 0 赞 0 分享

c#唯一值渲染实例代码

这篇文章主要介绍了c#唯一值渲染实例代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

淘宝IP地址库采集器c#代码

这篇文章主要介绍了淘宝IP地址库采集器c#代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

C#在后台运行操作(BackgroundWorker用法)示例分享

BackgroundWorker类允许在单独的专用线程上运行操作。如果需要能进行响应的用户界面,而且面临与这类操作相关的长时间延迟,则可以使用BackgroundWorker类方便地解决问题,下面看示例
收藏 0 赞 0 分享

c#文本加密程序代码示例

这是一个加密软件,但只限于文本加密,加了窗口控件的滑动效果,详细看下面的代码
收藏 0 赞 0 分享

c#生成站点地图(SiteMapPath)文件示例程序

这篇文章主要介绍了c#生成站点地图(SiteMapPath)文件的示例,大家参考使用
收藏 0 赞 0 分享

C# 键盘Enter键取代Tab键实现代码

这篇文章主要介绍了C# 键盘Enter键取代Tab键实现代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

C# WinForm导出Excel方法介绍

在.NET应用中,导出Excel是很常见的需求,导出Excel报表大致有以下三种方式:Office PIA,文件流和NPOI开源库,本文只介绍前两种方式
收藏 0 赞 0 分享

C#串口通信程序实例详解

在.NET平台下创建C#串口通信程序,.NET 2.0提供了串口通信的功能,其命名空间是System.IO.Ports,创建C#串口通信程序的具体实现是如何的呢?让我们开始吧
收藏 0 赞 0 分享
查看更多