C#WinForm读取电子秤数据网口通讯
|
admin
2025年8月16日 22:43
本文热度 104
|
using System.Net.Sockets;
namespace WinFormsApp2
{
public partial class FormMeterUdp : Form
{
public FormMeterUdp()
{
InitializeComponent();
this.FormClosing += MainForm_FormClosing;
}
private int _localPort=60001;
private Socket _udpServer;
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
_udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_udpServer.Bind(new IPEndPoint(IPAddress.Any, _localPort));
Task.Run(new Action(() =>
{
EndPoint remote = new IPEndPoint(IPAddress.Any, _localPort);
while (true)
{
if (_udpServer.Available < 1)
continue;
try
{
byte[] data = new byte[1024];
int len = _udpServer.ReceiveFrom(data, ref remote);
if (len == 0)
continue;
string receivemsg = Encoding.Default.GetString(data, 0, len);
if (string.IsNullOrEmpty(receivemsg))
continue;
DataReceived(receivemsg);
}
catch (Exception)
{
continue;
}
}
}));
}
catch (Exception ex)
{
MessageBox.Show($"打开失败: {ex.Message}");
}
}
private void DataReceived(string receivemsg)
{
string data = receivemsg;
this.BeginInvoke(new Action(() =>
{
txtReceived.AppendText($"{data}\r\n");
txtReceived.ScrollToCaret();
int SignStart = data.IndexOf(":");
if (SignStart < 0) return;
int NumberStart = 5;
int NumberBits = 5;
string dataPart = data.Substring(SignStart + NumberStart, NumberBits);
txtSend.Invoke(new Action(() =>
{
txtSend.Text = dataPart;
}));
}));
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (_udpServer != null)
_udpServer.Close();
}
}
}
阅读原文:原文链接
该文章在 2025/8/18 11:04:28 编辑过