一個掃碼槍遵循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); } } }新聞熱點
疑難解答