我已经在侦听器和客户端中使用了其他应用程序,并且侦听器的stream.read()只读取一次,而客户端的stream.write()仅写入一次,这是同一件事。
这是侦听器的循环:
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();
}
在第一次迭代之后,它只是阻塞并且即使连接断开也没有收到任何东西,它一直在阻塞,但是经过一段时间后,它给了我这个例外:
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
客户端第二个stream.write()上的异常:
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
我认为这可能是防火墙问题,如果是的话,有人可以告诉我它为什么会发生以及如何解决吗?预先谢谢你。
编辑:在第一个stream.read()之后,stream.DataAvailable为false,因此它不是What are some reasons NetworkStream.Read would hang/block?的副本
注意:侦听器的代码和客户端的代码均来自https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcplistener?view=netframework-4.7.2#examples和https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=netframework-4.7.2#examples