从TCP / IP设备接收数据

时间:2012-08-13 08:33:42

标签: c# tcp ip device

在我工作的地方,我们目前使用的是一个使用连接到我们网络的手持扫描器的时钟输入系统。我想知道是否有通过C#连接到此设备并从该设备接收任何输入的方法。或者,就此而言,以类似方式连接的任何其他输入设备。如果有的话,如果有人可以给我一些指导,让我开始,或建议在哪里看。

1 个答案:

答案 0 :(得分:1)

  

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

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

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

托管数据(服务器):

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.");
        }
    }
}