Java 服务器/客户端应用程序仅在按 Enter 键时显示消息

标签 java sockets networking port serversocket

服务器端:

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();
        }
    }
}

客户端:

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();
        }
    }
}

我的例子中的代码对我来说很有意义,我似乎无法弄清楚为什么仍然需要按下回车键,它与 .readLine() 有关系吗? 我查看了以下帖子Server Client in Java only displays message when I press enter ,但是提供的解决方案并不能解决问题。

注意:最初 while 循环中没有 if 语句。我认为这是一个问题,因为 while 循环可能会卡在其中一行,等待用户/服务器输入。因此,实现 if 语句允许它跳过等待部分并重新运行循环。

最佳答案

事实证明我混淆了变量。 while 循环应该是:

 while ((userInput=input.readLine())!="EXIT") {

它已修复,但仍然存在一些其他问题

关于Java 服务器/客户端应用程序仅在按 Enter 键时显示消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36770868/

相关文章:

Java 套接字编程 - 无法在 Android 4.1 中运行?

java - 在java中通过套接字发送大数据

c++ - 代码内联工作,但在类里面

mysql - Django和mysql在不同服务器上的性能

java - 如何在 Java 中创建 macOS 风格的蓝色默认按钮?

node.js - socket.io - socket.send 不传送消息

java - 部署多模块Play项目

JAVA:在客户端使用select

java - Android 上的批量/通配 rune 件删除

java - 如何在 AuthenticationSuccessHandler 中检索 session 范围的 bean?