一个扫码枪遵循TCP协议,通过改代码即可获取扫码枪所扫描的信息;(有一个串口服务器);
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Diagnostics; using System.Net; namespace Demo_Net { //本机为服务端 //下午加一个判断网络是否连接;以及做出相应的判断; class Program { static Socket msock; static void Main(string[] args) { //先判断是否ping通: string ips = \"10.18.14.111\"; string str = NetConnect(ips); Console.WriteLine(str); Console.ReadLine(); } //通过ping的方法判断是否连接; private static string NetConnect(string ip) { Process p = new Process(); p.StartInfo.FileName = \"cmd.exe\"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = false; string pingstr; p.Start(); p.StandardInput.WriteLine(\"ping -n 1 \" + ip); p.StandardInput.WriteLine(\"exit\"); string strRst = p.StandardOutput.ReadToEnd(); if (strRst.IndexOf(\"(0% 丢失)\") != -1) { pingstr = \"连接成功\"; //定义socket连接 需要的本机ip以及相应的端口; msock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var localIP = new IPEndPoint(IPAddress.Parse(\"10.18.14.23\"), 10001); msock.Bind(localIP); //自己定义最大网络连接数 msock.Listen(10); //新建线程处理; Thread th = new Thread(delegate() { Rec(); }); th.IsBackground = true; th.Start(); } else { pingstr = \"连接超时\"; } p.Close(); return pingstr; } //监听是否有链接,新开线程处理 static void Rec() { do { Socket s = msock.Accept(); Thread th = new Thread(delegate() { Parse(s); }); th.IsBackground = true; th.Start(); } while (true); } //有链接时处理获取的信息 static void Parse(Socket s) { do { byte[] b = new byte[1000]; int l = s.Receive(b); b = b.Take(l).ToArray(); string rs = string.Empty; for (int i = 0; i < b.Length; i++) { rs = rs + b[i].ToString(); } //解码 Console.WriteLine(Encoding.ASCII.GetString(b, 0, l)); } while (true); } } }
本文地址:https://www.stayed.cn/item/23110
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我