C# 触发基恩士扫码枪扫码并获取扫码结果

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace KEYENCE90340;

class Program
{
    static Socket ClientSocket;
    static void Main(string[] args)
    {
        String IP = "192.168.100.100";
        int port = 9004;

        IPAddress ip = IPAddress.Parse(IP);  //将IP地址字符串转换成IPAddress实例
        ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
        IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的ip和端口号初始化IPEndPoint实例
        ClientSocket.Connect(endPoint);  //与远程主机建立连接


        Console.WriteLine("开始发送消息");
        WriteMessage("开始发送消息。" + DateTime.Now);
        byte[] message = Encoding.ASCII.GetBytes("LON\r");  //通信时实际发送的是字节数组,所以要将发送消息转换字节
        ClientSocket.Send(message);
        Console.WriteLine("发送消息为:" + Encoding.ASCII.GetString(message));
        WriteMessage("发送消息为:" + Encoding.ASCII.GetString(message) + "。" + DateTime.Now);
        byte[] receive = new byte[1024];
        int length = ClientSocket.Receive(receive);  // length 接收字节数组长度
        Console.WriteLine("接收消息为:" + Encoding.ASCII.GetString(receive));
        var result = Encoding.ASCII.GetString(receive);
        result = result.Substring(0, result.IndexOf("\r"));
        WriteMessage("接收消息为:" + result + "。" + DateTime.Now);
        ClientSocket.Close();  //关闭连接
    }


    /// <summary>
    /// 输出指定信息到文本文件
    /// </summary>
    /// <param name="msg">输出信息</param>
    public static void WriteMessage(string msg)
    {
        using (FileStream fs = new FileStream(@"D:\KEYENCE90340.txt", FileMode.OpenOrCreate, FileAccess.Write))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.BaseStream.Seek(0, SeekOrigin.End);
                sw.WriteLine("{0}\n", msg, DateTime.Now);
                sw.Flush();
            }
        }
    }

}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值