2

我有一个 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 个字符或更少,则此方法可以正常工作,但如果更多,则不能。

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

4

1 回答 1

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手动对象)

于 2013-08-09T14:19:07.147 回答