如何使用UdpClient进行通讯
应用场景
最近一个项目因为需要跟客户的欧姆龙PLC进行通讯,客户指定了UDP方式,并且需要一直读取某个地址的值。而之前一直使用的HPSocket的绑定事件机制不是很适合这样的业务场景,因此今天花时间了解了一下System.Net.Sockets.UdpClient,重新写了一个udpclient的通讯功能。
客户端代码
demo最终效果界面:程序【启动】后会持续的往64地址发送读取指令,比如拍照指令,移动指令等。
关键代码
private void ProcessThread() { while (IsStarted) { try { sendDone.Reset(); client.Connect(txtIp.Text,int.Parse(txtPort.Text)); //800002006F00006400000101820064000001 string orimsgD0 = "800002006F00006400000101820064000001"; byte[] msgD0 = strToToHexByte(orimsgD0); client.Send(msgD0, msgD0.Length); client.BeginReceive(EndReceive, client); sendDone.WaitOne(); Thread.Sleep(200); } catch (Exception ex) { ShowInfo(ex.Message); IsStarted = false; continue; } } } private void EndReceive(IAsyncResult ar) { try { var s = ar.AsyncState as UdpClient; if (s != null) { UdpClient udpClient = s; IPEndPoint ip = null; Byte[] receiveBytes = udpClient.EndReceive(ar, ref ip); string msg = Encoding.UTF8.GetString(receiveBytes); ShowInfo(msg); ShowInfo("处理完成...你继续"); sendDone.Set(); } } catch (Exception ex) { //处理异常 ShowInfo(ex.Message); } }
希望这篇文章能帮助到大家。