c#利用Forms.Timer定时检测Tcp连接状态

目的:本地创建客户端连接服务器端,如果连接正常显示连接正常如果连接异常显示连接异常。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;

namespace BarcodeScanner
{
    public partial class Form2 : Form
    {
        private TcpClient tcpClient = null;
        private object objectlock = new object();

        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            // 创建一个定时器,每秒钟检测一次TCP连接状态
            Timer timer = new Timer();
            timer.Interval = 100;
            timer.Tick += Timer_Tick;
            timer.Start();
        }

        private async void Timer_Tick(object sender, EventArgs e)
        {
            /*
                在你的代码中,你使用了tcpClient.Connected属性来检测TCP连接状态。
                但是需要注意的是,tcpClient.Connected属性只能检测到上一次Send或Receive操作的连接状态,并不能实时检测到连接是否断开。
                如果要实时检测TCP连接状态,可以尝试发送一个特定的心跳消息给服务器,并等待服务器的回复。如果在一定时间内没有收到服务器的回复,就可以认为连接已经断开。
            */
            bool connected = await Task.Run(()=>IsConnectedAsync());
            toolStripStatusLabel1.Text = connected ? "tcp连接正常" : "tcp连接异常";
            toolStripStatusLabel1.BackColor = connected ? Color.Green : Color.Red;
        }

        private async Task<bool> IsConnectedAsync()
        {
            if (tcpClient == null || !tcpClient.Connected)
            {
                lock (objectlock)
                {
                    if (tcpClient == null || !tcpClient.Connected)
                    {
                        try
                        {
                            // 创建一个新的TcpClient实例,并连接到服务器
                            tcpClient = new TcpClient("127.0.0.1", 60000);
                            return true;
                        }
                        catch (Exception)
                        {
                            return false;
                        }
                    }
                }
            }
            else
            {
                try
                {
                    // 获取网络流
                    NetworkStream stream = tcpClient.GetStream();

                    // 将字符串转换为字节数组
                    byte[] data = Encoding.UTF8.GetBytes(" ");

                    // 发送数据
                    await stream.WriteAsync(data, 0, data.Length);
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

            // 如果所有检测都失败,则返回false
            return false;
        }
    }
}

 

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值