Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java readUTF()函数中的服务器被阻止_Java_Server_Client - Fatal编程技术网

Java readUTF()函数中的服务器被阻止

Java readUTF()函数中的服务器被阻止,java,server,client,Java,Server,Client,我试图在我的客户机和服务器之间连续地共享信息,但是当服务器正在读取时,它被卡住了 首先,客户机发送一些关于自己的信息(id和str字符串变量) 客户端 out.writeUTF(id+" "+str); out.flush(); System.out.println("Do you want a room ?"); System.out.println("These are the available room"); String a4; while((a4=in.readUTF()) != n

我试图在我的客户机和服务器之间连续地共享信息,但是当服务器正在读取时,它被卡住了

首先,客户机发送一些关于自己的信息(id和str字符串变量)

客户端

out.writeUTF(id+" "+str);
out.flush();
System.out.println("Do you want a room ?");
System.out.println("These are the available room");
String a4;
while((a4=in.readUTF()) != null)
    System.out.println(a4);
System.out.println("Pick one"); // It doesn't print that
sc4 = new Scanner(System.in);
String str4 = sc4.next();
out.writeUTF(str4);
out.flush();
服务器

out.writeUTF(Room.getAllRooms());
out.flush();
System.out.println("Before read");
String res = in.readUTF(); // stuck here
System.out.println("After read");
.
.
.
所有房间的印刷在客户那里效果都很好。但就在我无法访问打印“选择一个”之后

服务器没有读取任何内容,但为什么服务器先读取而客户端不先写入

(我简化了代码,事实上我使用的是使用线程的主/从体系结构)

更新:问题已解决,请阅读下面的回复。(readUTF()从不变为null)

您不是被“卡住”而是被阻止,不是在“读取”中而是在
readUTF()
中,原因是对等方既没有发送任何内容也没有关闭连接。这是预期的行为。您有一个
writeUTF()
和一个永无止境的
readUTF()
s循环。考虑一下您的应用程序协议

顺便说一句,你有一个错误:

while((a4=in.readUTF()) != null)
    System.out.println(a4);

readUTF()
从不返回null。当对等方关闭连接时,它将抛出
EOFException

,看起来您在
处于
状态时试图做的事情太多了。尝试将其拆分为两部分,以便检查流,而不是字符串。谢谢,我现在明白了,您是否知道如何解决此问题?我可以获取房间数并循环此数字,但有最简单的方法吗?我通过删除所有“\n”来解决此问题,除了a4字符串中的最后一个“\n”。这样我就得到了整个字符串,没有任何循环。谢谢添加
\n
永远不会使您在循环中获得整个字符串。一个
writeUTF()
=一个
readUTF()
。奇怪的假设。