1

I'm unable to get input and output streams from socket, my code blocks everytime it reach the getInputStream/getOutputStream.

class Connection implements Runnable {
    private static final Logger logger = Logger.getLogger(Connection.class.getName());
    Socket connection = null;
    Boolean serverIsDown = false;
    Thread thread = null;
    ObjectInputStream ois = null;
    ObjectOutputStream oos = null;
    Context ctx = null;

    public Connection(Socket accept, Boolean serverIsDown) {
        logger.log(Level.INFO, "Connected" + accept.getRemoteSocketAddress());
        this.connection = accept;
        this.serverIsDown = serverIsDown;

        this.thread = new Thread(this, "Client Connection");
        this.thread.start();

    }

    public void init() throws IOException {
        while (true) {
            System.out.println("Hit enter to send object");
            System.in.read();
            Request request = new Request();
            oos.writeObject(request);
        }
    }

    @Override
    public void run() {
        try {
            this.ois = new ObjectInputStream(this.connection.getInputStream()); //Blocks here
            this.oos = new ObjectOutputStream(this.connection.getOutputStream());
            this.init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

There's no output errors when it blocks.

1
  • 1
    Always flush() the ObjectOutputStream before creating an ObjectInputStream. This is because the format has a header the ObjectInputStream reads in the constructor. Commented Oct 31, 2015 at 13:37

2 Answers 2

2

as the documentation mentioned : http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#ObjectInputStream(java.io.InputStream)

Creates an ObjectInputStream that reads from the specified InputStream. 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.

I suggest you use two threads handling input and output stream from accepted socket,to avoid blocking. and the other better way is to use thread pool and some async io (ex;selector) instead of assigning each accepted socket with a thread.

also refer to the other post as below: new ObjectInputStream() blocks

Sign up to request clarification or add additional context in comments.

Comments

0

You create a new stream for each object. Only create one output and one input stream. Object streams send header data which is maybe corrupted when you create a new stream.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.