سؤال

This is my code. When I run this, I get up to "Three and a Half" printed. (The prints are added for debugging since I don't know any other way.) After that, the execution hangs. No exceptions, no prompts, nothing. So what is wrong with my object creation? Each and every tutorial I see online has the same code, but mine won't work.

public class Connection {
    Socket socket;
    ObjectInputStream iStream;
    ObjectOutput outputStream;

    public Connection(Socket s) {
        try {
            System.out.println("One");
            socket = s;
            System.out.println("Two");
            outputStream = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
            System.out.println("Three");
            InputStream is = socket.getInputStream();
            System.out.println("Three and a Half");
            iStream = new ObjectInputStream(is);
            System.out.println("Four");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Thanks in advance.

هل كانت مفيدة؟

المحلول

It's in the Javadoc:

A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.

So the new ObjectInputStream is hanging because it's waiting on input. You need to create an ObjectOutputStream and send data through the socket.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top