本文给大家分享的是使用C#实现简单获取扫码枪信息代码,非常的简单实用,有需要的小伙伴可以参考下。
本文给大家分享的是使用C#实现简单获取扫码枪信息代码,非常的简单实用,有需要的小伙伴可以参考下。
本文给大家分享的是使用C#实现简单获取扫码枪信息代码,非常的简单实用,有需要的小伙伴可以参考下。
一个扫码枪遵循TCP协议,通过改代码即可获取扫码枪所扫描的信息;(有一个串口服务器);
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
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.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); } } } |
发表评论