把通讯封装成一个类“
该程序的特点有优势:
传统写法当条码扫描头停机、异常断电、网络异常等,通讯终端后,程序无法正常恢复连接,丢失数据引发故障,我写的程序,无论扫描头断电还是产线重启,都能第一时间重启连接并通讯上,稳定性很好。
这个也是在一个朋友老程序不断出问题后,找我帮忙,我给重新写的,试用后效果很不过,非常好用,再也没有发生过问题。
如果您有硬件的通讯访问难点和项目,可以联系我解决,譬如 RS232 485 422 串口通讯、以太网接口的仪器仪表通讯、OPC Server自动化数据PLC访问都可以,欢迎练习我 邮箱: 458978@qq.com 加我QQ 458978 验证填,你从博客园知道我QQ号码的即可!
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets ; using System.Threading; namespace CodeReaderClient.ConnectType { /// <summary> /// 458978@qq.com /// Niewei 苏州 2016-09-10 /// </summary> public class TCPConnectClass { /// <summary> /// 以太网通讯对象 /// </summary> public TcpClient MyTcpClient; /// <summary> /// 数据流操作 /// </summary> public NetworkStream MyNetworkStream; /// <summary> /// 条码结果 /// </summary> public string BarCodeStr = string.Empty; /// <summary> /// IP地址 /// </summary> public string _IPAddressStr = string.Empty; /// <summary> /// 通讯端口 /// </summary> public int _Port = 8080; /// <summary> /// 初始化 /// </summary> /// <param name="IPAddressStr"></param> /// <param name="Port"></param> public TCPConnectClass (string IPAddressStr,int Port) { _IPAddressStr = IPAddressStr; _Port = Port; MyTcpClient = new TcpClient(); Thread Td = new Thread(RunPorcedue); Td.IsBackground = true; Td.Start(); } /// <summary> /// 连接检查方法,保持断线重连 /// </summary> public void Connect() { try { if (!MyTcpClient.Connected) { IPAddress IPAddress1 = IPAddress.Parse(_IPAddressStr); MyTcpClient = new TcpClient(); MyTcpClient.Connect(IPAddress1, _Port); MyNetworkStream = MyTcpClient.GetStream(); } if (MyTcpClient.Connected) { MyNetworkStream = MyTcpClient.GetStream(); byte[] Buffer = new byte[] { 0x41 }; MyNetworkStream.Write(Buffer, 0, 1); } } catch (Exception) { } } /// <summary> /// 循环工作线程 /// </summary> private void RunPorcedue() { byte[] Buffer = new byte[128]; int Count = 0; while (true) { //检查连接//发送心跳包 Connect(); //解析接收到的数据 try { if (MyTcpClient .Available >0) { Buffer = new byte[128]; Count = MyNetworkStream.Read(Buffer, 0, Buffer.Length); if (Count > 0) { BarCodeStr = ExplanationByte(Buffer); } } } catch (Exception err) { string a = err.Message; } Thread.Sleep(100); } } /// <summary> /// 解析来自条码扫描头的字符串 /// </summary> /// <param name="Buffer"></param> /// <returns></returns> private string ExplanationByte(byte[] Buffer) { if (Buffer .Length >0) { string Value = System.Text.ASCIIEncoding.ASCII.GetString(Buffer, 0, Buffer.Length); Value = Value.Replace(" ", ""); Value = Value.Replace(" ", ""); Value = Value.Replace(" ", ""); return Value; } else { return string.Empty; } } } }
程序写好了,可以用网络调试助手来调试收发情况!