1

I'm connected to Barcode Reader which has an IP address over Ethernet and using the following (simplified) code:

using (TcpClient client = new TcpClient("192.168.20.41", 1002))
{
    using (NetworkStream stream = client.GetStream())
    {
        while (true)
        {
            int readCount;
            byte[] data = new byte[client.ReceiveBufferSize];

            while (stream.DataAvailable && (readCount = stream.Read(data, 0, client.ReceiveBufferSize)) != 0)
            {
                value += Encoding.UTF8.GetString(data, 0, readCount);
            }

            if (!string.IsNullOrWhiteSpace(value) && value.EndsWith(endOfLine))
            {
                OnRead(value);
                value = "";
            }

            //Thread.Sleep(200);
        }
    }
}

When I start my test app and scan some barcode its working fine, I can do as many scans as I want. Now, when I idle for at least 30 seconds and then scan a barcode then stream.DataAvailable keeps false, client.Available keeps 0, but client.Connected is still true. When I restart my app its working again until I idle again for 30 seconds.

Do I need to keep my client or stream alive? How would I do it?

Thanks in advance.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
Powerslave
  • 139
  • 1
  • 11
  • 1
    it's probably because the other side disconnected - `Connected` will not necessary be `false` in this case (see here http://stackoverflow.com/questions/2661764/how-to-check-if-a-socket-is-connected-disconnected-in-c) . As of how to keep the other side alive I have no clue (depends on your barcode-scanner i guess) but I would just add the check from the question I gave you and try to reconnect in case – Random Dev Apr 01 '15 at 04:20
  • Thank you, that helps. The reader has a "port timeout=30sec" property. – Powerslave Apr 01 '15 at 07:28

0 Answers0