发布网友 发布时间: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
}