public class SerProg {
static ServerSocket ser=null;
static Socket cli=null;
static ObjectInputStream ins=null;
static ObjectOutputStream outs=null
You need to create the ObjectOutputStream
before the ObjectInputStream
at both sides of the connection(!). When the ObjectInputStream
is created, it tries to read the object stream header from the InputStream
. So if the ObjectOutputStream
on the other side hasn't been created yet there is no object stream header to read, and it will block indefinitely.
Or phrased differently: If both sides first construct the ObjectInputStream
, both will block trying to read the object stream header, which won't be written until the ObjectOutputStream
has been created (on the other side of the line); which will never happen because both sides are blocked in the constructor of ObjectInputStream
.
This can be inferred from the Javadoc of ObjectInputStream(InputStream in):
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.
This is also described in section 3.6.2 of Fundamental networking in Java by Esmond Pitt.
You must make handshaking for streams. I mean that in client side, when you create a object input stream you must create a object output stream in server side.
//SERVER SIDE
Socket clientSocket = TcpServer.socket.accept();
// 1. input stream;
ObjectInputStream sInput = new ObjectInputStream(clientSocket.getInputStream());
// 2. output stream
ObjectOutputStream sOutput = new ObjectOutputStream(clientSocket.getOutputStream());
//CLIENT SIDE
Socket socket = new Socket(ip, port);
// 2. output stream
ObjectOutputStream sOutput = new (socket.getOutputStream());
// 1. input stream
ObjectInputStream sInput = new ObjectInputStream(socket.getInputStream());
I tried to show that how to make handshaking for streams.