1

在我工作的地方,我们目前使用一个打卡系统,该系统使用连接到我们网络的手持扫描仪。我想知道是否有办法通过 C# 连接到该设备并接收来自该设备的任何输入。或者,就此而言,以类似方式连接的任何其他输入设备。而且,如果是这样,是否有人可以给我一些指导以帮助我入门,或者建议在哪里寻找。

4

1 回答 1

2

如果有人可以给我一些指导让我开始,或者在哪里看。

我建议您查看“ System.Net ”命名空间。使用 或者我推荐的StreamReader,您可以轻松地在多个设备之间写入和读取流。StreamWriterNetworkStream

请看以下示例,了解如何托管数据并连接到主机以接收数据。

托管数据(服务器):

static string ReadData(NetworkStream network)
{
    string Output = string.Empty;
    byte[] bReads = new byte[1024];
    int ReadAmount = 0;

    while (network.DataAvailable)
    {
        ReadAmount = network.Read(bReads, 0, bReads.Length);
        Output += string.Format("{0}", Encoding.UTF8.GetString(
            bReads, 0, ReadAmount));
    }
    return Output;
}

static void WriteData(NetworkStream stream, string cmd)
{
    stream.Write(Encoding.UTF8.GetBytes(cmd), 0,
    Encoding.UTF8.GetBytes(cmd).Length);
}

static void Main(string[] args)
{
    List<TcpClient> clients = new List<TcpClient>();
    TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, 1337));
    //listener.ExclusiveAddressUse = true; // One client only?
    listener.Start();
    Console.WriteLine("Server booted");

    Func<TcpClient, bool> SendMessage = (TcpClient client) => { 
        WriteData(client.GetStream(), "Responeded to client");
        return true;
    };

    while (true)
    {
        if (listener.Pending()) {
            clients.Add(listener.AcceptTcpClient());
        }

        foreach (TcpClient client in clients) {
            if (ReadData(client.GetStream()) != string.Empty) {
                Console.WriteLine("Request from client");
                SendMessage(client);
             }
        }
    }
}

现在客户端将使用以下方法发送请求:

static string ReadData(NetworkStream network)
{
    string Output = string.Empty;
    byte[] bReads = new byte[1024];
    int ReadAmount = 0;

    while (network.DataAvailable)
    {
        ReadAmount = network.Read(bReads, 0, bReads.Length);

        Output += string.Format("{0}", Encoding.UTF8.GetString(
                bReads, 0, ReadAmount));
    }
    return Output;
}

static void WriteData(NetworkStream stream, string cmd)
{
    stream.Write(Encoding.UTF8.GetBytes(cmd), 0,
                Encoding.UTF8.GetBytes(cmd).Length);
}

static void Main(string[] args)
{
    TcpClient client = new TcpClient();
    client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1337));
    while (!client.Connected) { } // Wait for connection

    WriteData(client.GetStream(), "Send to server");
    while (true) {
        NetworkStream strm = client.GetStream();
        if (ReadData(strm) != string.Empty) {
            Console.WriteLine("Recieved data from server.");
        }
    }
}
于 2012-08-13T09:00:02.327 回答