I have 2 simple applications - server and client. For now, server just waiting for a client to connect, prints networkstream.DataAvailable status, freezes for 5 sec and prints networkstream.DataAvailable status again. Client does the same thing, except it doesn't wait for connection but connects to server. Server-side code:
static void Main(string[] args)
{
int port = 8880;
IPAddress localAddress = IPAddress.Parse("127.0.0.1");
TcpListener serverListener = new TcpListener(localAddress, port);
serverListener.Start();
TcpClient incomingConnection = serverListener.AcceptTcpClient();
IPEndPoint RemAddr = (IPEndPoint)incomingConnection.Client.RemoteEndPoint; ;
Console.WriteLine("Connection: {0}:{1}", RemAddr.Address, RemAddr.Port);
NetworkStream networkStream = incomingConnection.GetStream();
StreamWriter sw = new StreamWriter(networkStream, Encoding.UTF8) { AutoFlush = true };
Console.WriteLine("networkstream.DataAvailable is {0}", networkStream.DataAvailable);
Thread.Sleep(5000);
Console.WriteLine("networkstream.DataAvailable is {0}", networkStream.DataAvailable);
...
Client-side code:
static void Main(string[] args)
{
IPAddress remoteaddr = IPAddress.Parse("127.0.0.1");
int port = 8880;
TcpClient tcpclient = new TcpClient();
tcpclient.Connect(remoteaddr, port);
NetworkStream networkstream = tcpclient.GetStream();
StreamWriter sw = new StreamWriter(networkstream, Encoding.UTF8);
StreamReader sr = new StreamReader(networkstream, Encoding.UTF8);
Console.WriteLine("networkstream.DataAvailable is {0}", networkstream.DataAvailable);
Thread.Sleep(5000);
Console.WriteLine("networkstream.DataAvailable is {0}", networkstream.DataAvailable);
...
So, here I have a problem. On server side I have the following output:
Connection: 127.0.0.1:55919
networkstream.DataAvailable is False
networkstream.DataAvailable is False
On server side output is:
networkstream.DataAvailable is False
networkstream.DataAvailable is True
So client shows that there is data in my networkStream. But there is no any data! And this is a problem, because in my application I use networkstream.DataAvailable to detect if there any data sent from server. So, question is - what am I doing wrong? How to check availability of data properly?
Thomas Levesque answered my question in comments section:
From the server perspective, there is nothing to read, since the client didn't write anything. I think the StreamWriter writes the BOM when you create it, hence the 3 bytes. And sr.Read() tries to read a character, but there is nothing to read beyond the BOM, so it blocks. – Thomas Levesque 10 mins ago