Defending against no data

-1

I have this line of code:

NetworkStream tcpStream;
return IPAddress.NetworkToHostOrder(new BinaryReader(tcpStream).ReadInt32());

Occasionally, there is no data to read and that lines throws an exception.

System.IO.EndOfStreamException
  HResult=0x80070026
  Message=Unable to read beyond the end of the stream.
  Source=mscorlib
  StackTrace:
   at System.IO.__Error.EndOfFile()
   at System.IO.BinaryReader.FillBuffer(Int32 numBytes)
   at System.IO.BinaryReader.ReadInt32()
   ...

The Length property also doesn't seem to help. DataAvailable is highly unreliable. How do I defend against an empty message?

c#
.net
tcp
asked on Stack Overflow Jul 30, 2020 by Ivan • edited Jul 30, 2020 by Ivan

1 Answer

0

Why do you need that? You can use a StreamReader and a StreamWriter to easily send and receive a string. Then, you can handle that data, and get your int.

        static int Receive(NetworkStream nw)
        {
            using (var reader = new StreamReader(nw, Encoding.UTF8))
            {
                return Convert.ToInt32(reader.ReadLine());
            }
        }

        static void Send(NetworkStream nw, int num)
        {
            using (var writer = new StreamWriter(nw, Encoding.UTF8))
            {
                writer.WriteLine(num.ToString());
            }
        }

Tested and works.

answered on Stack Overflow Aug 1, 2020 by anti

User contributions licensed under CC BY-SA 3.0