I have used other apps with each the listener and the client and the same thing happens the listener's stream.read() only reads once and client's stream.write() only writes once.
here's the Listener's loop:
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.length)) != 0)
{
// Translate data bytes to a ASCII string.
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
}
// Shutdown and end connection
client.Close();
}
after the first iteration it just blocks and doesn't receive anything even when the connection is lost it keeps blocking, however after some time has passed it gives me this exception:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
same exception on the second stream.write() in the Client's side:
System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
I think this might be a firewall problem and if so, can someone tell me why it happens and how to fix it ? Thank you in advance.
Edit: stream.DataAvailable is false after the first stream.read() so it's not a duplicate of What are some reasons NetworkStream.Read would hang/block?
Note: the Listener's code and the Client's were both taken from https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcplistener?view=netframework-4.7.2#examples and https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=netframework-4.7.2#examples