仅从TCP / IP条形码阅读器获取一半条形码

时间:2013-08-09 13:22:03

标签: c# barcode tcpclient networkstream tcp-ip

我有一台Microscan TCP / IP条形码阅读器。我目前正在使用以下代码连接到它并在读取时检索条形码:

// responseData string will be the barcode received from reader
string responseData = null;

TcpClient client = new TcpClient("10.90.10.36", 2001);

// The "getData" is just a generic string to initiate connection
Byte[] sentData = System.Text.Encoding.ASCII.GetBytes("getData");
NetworkStream stream = client.GetStream();
stream.Write(sentData, 0, sentData.Length);
Byte[] receivedData = new Byte[20];
Int32 bytes = stream.Read(receivedData, 0, receivedData.Length);

for (int i = 0; i < bytes; i++)
{
    responseData += Convert.ToChar(receivedData[i]);
}

// Closes the socket connection.
client.Close();

我遇到的问题是,当条形码为15时,我只能获得10个字符。一切正常,直到Int32 bytes = stream.Read(receivedData, 0 receivedData.Length);行。 Read调用返回10而不是15。我试过用几种不同的方式修改代码,但是所有这些代码都像正常一样返回了10个字符。如果条形码不超过10个字符,则可正常工作,但如果条形码更多,则无法正常工作。

我不认为这是扫描仪的问题,但我也在检查它。有人有什么想法吗?

1 个答案:

答案 0 :(得分:2)

尝试类似:

// responseData string will be the barcode received from reader
string responseData = null;

using (TcpClient client = new TcpClient("10.90.10.36", 2001))
{
    using (NetworkStream stream = client.GetStream())
    {
        byte[] sentData = System.Text.Encoding.ASCII.GetBytes("getData");
        stream.Write(sentData, 0, sentData.Length);

        byte[] buffer = new byte[32];
        int bytes;

        while ((bytes = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            for (int i = 0; i < bytes; i++)
            {
                responseData += (char)buffer[i];
            }
        }
    }
}

while周期将重复,同时有新的字符可以接收。我甚至在你的代码周围添加了一些using(最好使用它们而不是Close手动对象)

相关问题