C#通过网线接收电子秤自动返回信息,电子秤返回的信息是一条一条的_百 ...

发布网友 发布时间:2025-01-14 19:42

我来回答

1个回答

热心网友 时间:2025-01-14 22:02

private void button1_Click(object sender, EventArgs e)

{

try
{
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("192.168.1.150"), 4001);
Thread th = new Thread(ReadMsg);
th.IsBackground = true;
th.Start(client); //开始新线程。用来与设备通信,不防碍主线程工作
}
catch (Exception ex)
{
throw (ex);
}
}

private void ReadMsg(object client)
{
NetworkStream netStream = ((TcpClient)client).GetStream();
byte[] sendBytes = System.Text.Encoding.Default.GetBytes("!0J0001A\r\n");
netStream.Write(sendBytes, 0, sendBytes.Length); //发送信息
byte[] readBuffer = new byte[1024];
int count = 0;
string msg = "";
do{
count=netStream.Read(readBuffer,0,1024);
msg += System.Text.Encoding.ASCII.GetString(readBuffer, 0,count);
}while(count ==1024); //读完所有的信息
showMsg = new ShowMsgEventHandler(setText);
showMsg(msg);

}
public delegate void ShowMsgEventHandler(string msg);
ShowMsgEventHandler showMsg; 使用委托实现跨线程
private void setText(string msg)
{
textBox1.Text=msg

}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com