ObjectOutputStream hanging forever

2019-06-04 04:30发布

I have a client that connects to a server using SSLSocket. Next, I try to create an OOS with ObjectOutputStream oos = new ObjectOutputStream(sslsocket.getOutputStream());

If everything is working well on the server side, this is fine. However, I would like to put something in place on my client side that tries to create the ObjectOutputStream, but if it hasn't happened in 60 seconds, log the error and continue processing. I don't see any timeout options for this. Any examples of how this could be done?

     SSLSocket sslsocket;
     try {
            System.setProperty("javax.net.ssl.trustStore", <myKeystore>);
            System.setProperty("javax.net.ssl.trustStorePassword", <myPW>);
            SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            sslsocket = (SSLSocket) sslsocketfactory.createSocket(InetAddress.getLocalHost(), <myPort>);

     } catch (Throwable e) {
            logger.logError(e.getMessage());
            return null;
     }

      // This is where it hangs forever
      ObjectOutputStream oos = new ObjectOutputStream(sslsocket.getOutputStream());
      oos.flush(); // never gets here
      oos.writeObject(orders);

      ObjectInputStream ois = new ObjectInputStream(sslsocket.getInputStream());

1条回答
Bombasti
2楼-- · 2019-06-04 05:12

You have to create the ObjectOutputStream before the ObjectInputStream.

EDIT: See comments below. The real problem was a slow SSL handshake, which happens in the first I/O on the socket, and during which reads are performed as well as writes. So the solution was to set a read timeout.

查看更多
登录 后发表回答