C#实现简单获取扫码枪信息代码
一个扫码枪遵循TCP协议,通过改代码即可获取扫码枪所扫描的信息;(有一个串口服务器);
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Threading;
usingSystem.Diagnostics;
usingSystem.Net;
namespaceDemo_Net
{
//本机为服务端
//下午加一个判断网络是否连接;以及做出相应的判断;
classProgram
{
staticSocketmsock;
staticvoidMain(string[]args)
{
//先判断是否ping通:
stringips="10.18.14.111";
stringstr=NetConnect(ips);
Console.WriteLine(str);
Console.ReadLine();
}
//通过ping的方法判断是否连接;
privatestaticstringNetConnect(stringip)
{
Processp=newProcess();
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;
stringpingstr;
p.Start();
p.StandardInput.WriteLine("ping-n1"+ip);
p.StandardInput.WriteLine("exit");
stringstrRst=p.StandardOutput.ReadToEnd();
if(strRst.IndexOf("(0%丢失)")!=-1)
{
pingstr="连接成功";
//定义socket连接需要的本机ip以及相应的端口;
msock=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
varlocalIP=newIPEndPoint(IPAddress.Parse("10.18.14.23"),10001);
msock.Bind(localIP);
//自己定义最大网络连接数
msock.Listen(10);
//新建线程处理;
Threadth=newThread(delegate()
{
Rec();
});
th.IsBackground=true;
th.Start();
}
else
{
pingstr="连接超时";
}
p.Close();
returnpingstr;
}
//监听是否有链接,新开线程处理
staticvoidRec()
{
do
{
Sockets=msock.Accept();
Threadth=newThread(delegate(){
Parse(s);
});
th.IsBackground=true;
th.Start();
}while(true);
}
//有链接时处理获取的信息
staticvoidParse(Sockets)
{
do
{
byte[]b=newbyte[1000];
intl=s.Receive(b);
b=b.Take(l).ToArray();
stringrs=string.Empty;
for(inti=0;i<b.Length;i++)
{
rs=rs+b[i].ToString();
}
//解码
Console.WriteLine(Encoding.ASCII.GetString(b,0,l));
}while(true);
}
}
}