ObjectInputStream挂起

时间:2014-03-19 18:58:51

标签: java sockets

我的" Socket to ServerSocket" -implementation的客户端看起来像这样,但它永远不会超过ObjectInputStream - 初始化。我已经尝试注释掉该行,然后执行以下print语句。连接(至少最初)成功,ServerSocket报告连接成功。

客户端

try(
    Socket socket = new Socket("localhost", 4444);
    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
    ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
) { 
    System.out.println("Connection and IO established");

} catch (IOException e) {
    e.printStackTrace();
}

服务器

while (true) {
    Socket clientSocket = serverSocket.accept();
    System.out.println("Client has connected!");         // This always prints
    new Thread(new ServerThread(clientSocket)).start();
    System.out.println("ServerThread has started");      // This as well
}

1 个答案:

答案 0 :(得分:0)

ObjectInputStream阻塞等待构建对等体的ObjectOutputStream。很明显,如果你在堆栈中有一个BufferedOutputStream,那么peer不会构造一个,或者可能需要在构造之后立即刷新它。

或者可能它本身就是挂起构建ObjectInputStream因为你的客户没有构建ObjectOutputStream.解决方法是始终构造和刷新<{1}}之前的ObjectOutputStream ObjectInputStream.