using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using Modbus.Device;
using thinger.cn.DataConvertHelper;
using NModbusHelper;
namespace NmodbusPractice2
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
a = true;
if (a)
{
label1.Text = "通信已连接";
}
else
{
label1.Text = "通信已断开";
}
}
static bool a;
string ip = "127.0.0.1";
int port = 502;
CancellationTokenSource cts1 = new CancellationTokenSource();
CancellationTokenSource cts2 = new CancellationTokenSource();
NmodbusTCPhelper objTcp = new NmodbusTCPhelper();
private bool IsConnected = false;
private System.Windows.Forms.Timer updateTimer = new System.Windows.Forms.Timer();
ushort[] res;
List<float> floatArray;
private void Addinfo(string info)
{
this.isInfo.Items.Insert(
0, DateTime.Now.ToString("HH:mm:ss") + " " + info + Environment.NewLine);
}
private void btnConnect_Click(object sender, EventArgs e)
{
IsConnected = objTcp.Connect(ip, port);
Addinfo(IsConnected ? "连接成功" : "连接失败");
}
private void btnRead_Click(object sender, EventArgs e)
{
this.updateTimer.Interval = 1000;
this.updateTimer.Tick += UpdateTimer_Tick;
this.updateTimer.Start();
if (res != null)
{
Addinfo("读取成功");
}
}
private void UpdateTimer_Tick(object sender, EventArgs e)
{
string iAddress = this.txtVarAdd.Text;
int iLength = Convert.ToUInt16(this.numCount.Text);
res = objTcp.ReadKeepReg(iAddress, iLength);
//Uint
//this.isInfo.Items.Add(res.ToString());
//for (int i = 0; i < res.Length; i++)
//{
// this.isInfo.Items.Add(res[i].ToString());
//}
//float
floatArray = objTcp.AnalyseData_4x(res,iAddress);
for (int i = 0; i < floatArray.ToArray().Length; i++)
{
this.isInfo.Items.Add(floatArray.ToArray()[i].ToString());
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
objTcp.Disconnect();
Addinfo("断开连接");
}
private void ChangeRTU_Click(object sender, EventArgs e)
{
FrmRTU frmRTU = new FrmRTU();
frmRTU.Show();
}
private void FrmMain_Load(object sender, EventArgs e)
{
}
private void label1_TextChanged(object sender, EventArgs e)
{
string b = "通信已连接";
Task.Run(() =>
{
if (!a)
{
Thread.Sleep(3000);
a = true;
label1.Invoke(new Action<string>(t=>this.label1.Text=t), b);
}
}, cts1.Token);
}
private void button1_Click(object sender, EventArgs e)
{
string b = "通信已断开";
a = false;
label1.Invoke(new Action<string>(t => this.label1.Text = t), b);
//Task.Run(() =>
//{
// a = false;
// label1.Invoke(new Action<string>(t => this.label1.Text = t), b);
//}, cts2.Token);
}
}
}
C# socket 断线重连 测试
最新推荐文章于 2024-08-06 18:21:23 发布