C#實現簡單擷取掃碼槍資訊代碼_C#教程

來源:互聯網
上載者:User

一個掃碼槍遵循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);          }  } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.