Java Socket Programming

Malachi picture Malachi · Jan 23, 2009 · Viewed 14.8k times · Source

I am building a simple client/server application using java sockets and experimenting with the ObjectOutputStream etc.

I have been following the tutorial at this url http://java.sun.com/developer/technicalArticles/ALT/sockets starting half way down when it talks about transporting objects over sockets.

See my code for the client http://pastebin.com/m37e4c577 However this doesn't seem to work and i cannot figure out what's not working. The code commented out at the bottom is directly copied out of the tutorial - and this works when i just use that instead of creating the client object.

Can anyone see anything i am doing wrong?

Answer

Mike Houston picture Mike Houston · Jan 23, 2009

The problem is the order you are creating the streams:

In the server from the article (which I assume is what you are using), when a new connection is opened, the server opens first an input stream, and then an output stream:

public Connect(Socket clientSocket) {
 client = clientSocket;
 try {
  ois = new ObjectInputStream(client.getInputStream());
  oos = new ObjectOutputStream(client.getOutputStream());
 } catch(Exception e1) {
     // ...
 }
 this.start();
}

The commented example code uses the reverse order, first establishing the output stream, then the input stream:

// open a socket connection
socket = new Socket("localhost", 2000);
// open I/O streams for objects
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());

But your code does it the other way around:

server = new Socket(host, port);
in = new ObjectInputStream(server.getInputStream());
out = new ObjectOutputStream(server.getOutputStream());

Establishing an output stream/input stream pair will stall until they have exchanged their handshaking information, so you must match the order of creation. You can do this just by swapping lines 34 and 35 in your example code.