有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在创建ObjectInputStream后无法看到打印消息

我编写了以下程序。如您所见,我在ObjectInputStream对象ois创建之后放置了一条打印消息。我有一个服务器在端口9090上打开。从上面的netstat消息中可以看到

sudo netstat -al | grep 9090
tcp6       0      0 [::]:9090               [::]:*                  LISTEN   

我不知道为什么屏幕上会显示打印信息

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class MyClient {    
    public static void main(String[] args) {
        int count = 0;
        try {
            /*
             * Create a connection to the server socket on the server application
             */
             InetAddress address = InetAddress.getByName("localhost");
             Socket socket = new Socket(address, 9090);

            /*
             * Read and display the response message sent by server application
             */
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            System.out.println("Created client socket and Input Stream Reader");
            while (true) {
                if (count < 1000) {
                    String message = (String) ois.readObject();
                    System.out.println("OFMessage: " + message);
                    count++;
                } else {
                    break;
                }
            }
            ois.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    {}的构造函数从流中读取数据——它基本上读取头信息

    因此,如果与您交谈的服务器没有写入任何数据,那么您的程序将只是坐在那里,等待真正写入头

    如果在运行这段代码时在调试器中点击break,我想您会发现堆栈跟踪包含ObjectInputStream.readStreamHeader