当前位置: 移动技术网 > IT编程>开发语言>c# > C#实现简单获取扫码枪信息代码

C#实现简单获取扫码枪信息代码

2019年07月18日  | 移动技术网IT编程  | 我要评论

一个扫码枪遵循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);
      
    }
  }
 
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网