C#使用Socket实现心跳

本文介绍了如何使用C#编程语言通过Socket实现服务器端的心跳机制。内容包括Server端的具体代码实现,展示了心跳包的发送与接收,确保客户端与服务器间的连接保持活跃。
摘要由CSDN通过智能技术生成

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 = "";

                //等待接收消息
 
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值