0

我编写了以下程序。如您所见,我在创建 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();
        }
    }
}
4

1 回答 1

2

从流中读取的构造函数ObjectInputStream- 它基本上读取标题信息。

因此,如果您正在与之交谈的服务器没有写入任何数据,您的程序将坐在那里,等到实际写入标头。

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

于 2013-08-04T07:15:19.720 回答