[英]Java server/client application only displays messages upon pressing enter
Server Side: 服务器端:
try {
ServerSocket server_socket=new ServerSocket(port_number);
Socket client_socket= server_socket.accept();
PrintWriter output = new PrintWriter(client_socket.getOutputStream(),true);
BufferedReader input = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
BufferedReader stdIn=new BufferedReader(new InputStreamReader(System.in));
String userInput, clientOutput;
while ((userInput=stdIn.readLine())!="EXIT") {
if ((clientOutput=input.readLine())!=null) {
System.out.println("Client: "+clientOutput);
} if (userInput!=null) {
output.println(userInput);
output.flush();
}
}
}
Client Side: 客户端:
try {
Socket client_socket= new Socket(hostname,port_number);
PrintWriter output = new PrintWriter(client_socket.getOutputStream(),true);
BufferedReader input = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
BufferedReader stdIn=new BufferedReader(new InputStreamReader(System.in));
String userInput,serverOutput;
while ((userInput=stdIn.readLine())!="EXIT") {
if ((serverOutput=input.readLine())!=null) {
System.out.println("Server: "+serverOutput);
} if (userInput!=null) {
output.println(userInput);
output.flush();
}
}
}
The code in my case makes sense to me, I cant seem to figure out why an enter still needs to be pressed, does it have something to do with .readLine()
? 就我而言,代码对我来说很有意义,我似乎无法弄清为什么仍然需要按下Enter键,它与.readLine()
吗? I checked out the following post Server Client in Java only displays message when I press enter , however the solution provided does not fix the situation. 我签出了以下帖子,当按Enter时,Java中的Server Client仅显示消息 ,但是提供的解决方案无法解决这种情况。
Note: Initially there were no if statements in the while loop. 注意:最初,在while循环中没有if语句。 The way I saw this to be an issue was that the while loop may get stuck on one of the lines, waiting for user/server input. 我认为这是一个问题,而while循环可能会停留在其中一行上,等待用户/服务器输入。 Therefore implementing if statements allowed it to skip the waiting portion and re-run the loop. 因此,实现if语句允许它跳过等待部分并重新运行循环。
Turns out I mixed my variables up. 原来我把变量混在一起了。 The while loops should be: while循环应为:
while ((userInput=input.readLine())!="EXIT") {
It fixed it, but there are some other issues still present 它已修复,但仍然存在其他一些问题
does it have something to do with .getLine()? 它与.getLine()有关系吗?
Yes. 是。 If you look at the Javadoc for BufferedReader#readLine() , it clearly states that an end of line character terminates the String to be read: 如果您查看BufferedReader#readLine()的Javadoc ,则会清楚地指出行尾字符会终止要读取的String:
Reads a line of text. 读取一行文本。 A line is considered to be terminated by any one of a line feed ('\\n'), a carriage return ('\\r'), or a carriage return followed immediately by a linefeed. 一行被认为由换行符('\\ n'),回车符('\\ r')或回车符后立即换行符中的任何一个终止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.