0

I have this server/client model for a game but it keeps getting stuck at the ObjectInputStream initialization.

Here is the code for the client's start method:

public void start(){
try {
        Socket s = new Socket("127.0.0.1", 24680);
        Thread.sleep(1000);
        ois = new ObjectInputStream(s.getInputStream()); // stuck here
        oos = new ObjectOutputStream(s.getOutputStream());
        startGame();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

here is the server code:

try {
    InputStream fis = socket.getInputStream();
    ObjectInputStream ois = new ObjectInputStream(fis);
    while (true) {
        ArrayList < Dot > lists = (ArrayList < Dot > ) ois.readObject();
        for (Socket s: sockets) {
            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
            oos.writeObject(lists);
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

Thanks in advance!

user207421
  • 305,947
  • 44
  • 307
  • 483
sguan
  • 1,039
  • 10
  • 26
  • Does netstat show a connection? Where is the server code that creates the server socket? There's not enough information here to help. – Jim Garrison Oct 05 '15 at 00:29
  • can it be a network connectivity issue? try connecting to your server with telnet first. – ilj Oct 05 '15 at 01:20
  • You had three goes at this. Only one of them can be correct. You are blocked at `new ObjectInputStream()`, not `getInputStream()` or `new ObjectOutputStream().` – user207421 Oct 05 '15 at 01:48
  • @JimGarrison If there wasn't a connection there wouldn't be a `Socket` either. – user207421 Oct 05 '15 at 01:51
  • Provide the complete code where you define the server socket and sockets collection. – James Jithin Oct 05 '15 at 01:59

1 Answers1

9

You need to construct the ObjectOutputStream before the ObjectInputStream at at least one end, preferably both to avoid accidents. Otherwise new ObjectInputStream() blocks trying to read the stream header which hasn't been written yet by the peer's new ObjectOutputStream(), because he also is blocked in new ObjectInputStream().

Other notes:

  • You must use the same object streams for the life of the socket, at both ends, unlike your current code. The reason is the same: the stream header. If you keep creating new ObjectOutputStreams you will keep writing new stream headers, which the peer won't expect or understand.
  • Remove the sleep(). There is no need for sleeps in networking code. They are just literally a waste of time. Cargo-cult programming.
user207421
  • 305,947
  • 44
  • 307
  • 483