C#實現(xiàn)簡單獲取掃碼槍信息代碼
更新時間:2016年07月26日 10:33:38 投稿:hebedich
本文給大家分享的是使用C#實現(xiàn)簡單獲取掃碼槍信息代碼,非常的簡單實用,有需要的小伙伴可以參考下。
一個掃碼槍遵循TCP協(xié)議,通過改代碼即可獲取掃碼槍所掃描的信息;(有一個串口服務器);
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 { //本機為服務端 //下午加一個判斷網(wǎng)絡是否連接;以及做出相應的判斷; 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); //自己定義最大網(wǎng)絡連接數(shù) msock.Listen(10); //新建線程處理; Thread th = new Thread(delegate() { Rec(); }); th.IsBackground = true; th.Start(); } else { pingstr = "連接超時"; } p.Close(); return pingstr; } //監(jiān)聽是否有鏈接,新開線程處理 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); } } }
相關文章
C#動態(tài)執(zhí)行字符串(動態(tài)創(chuàng)建代碼)的實例代碼
在編寫C#程序的時候,有時我們需要動態(tài)生成一些代碼并執(zhí)行。然而C#不像JavaScript有一個Eval函數(shù),可以動態(tài)的執(zhí)行代碼。所有這些功能都要我們自己去完成2013-03-03