目的:本地创建客户端连接服务器端,如果连接正常显示连接正常如果连接异常显示连接异常。
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;
}
}
}