I am trying to implement a full duplex TCP connection between two applications.
My gist of the idea is to do the following :
Client
socket.connect(ServerAddress,Timeout);
socketArray.add(socket);
outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.writeObject(message);
outputStream.flush();
/** Wait for reply**/
inputStream = new ObjectInputStream(socket.getInputStream());
message = (Message)inputStream.readObject();
if (message.type == X) {
replyToServer(message,socketArray);
}
replyToServer(Message,socketArray) {
for(Socket socket : socketArray) {
outputStream = new ObjectOutputStream(socket.getOutputStream()); // **getting streamCorruptedException** here
outputStream.writeObject(message);
outputStream.flush();
}
}
Server
Here I listen to the incoming connections, and dependent on the message type, I want to reply to it after changing some parameters of the message.
inputStream = new ObjectInputStream(clientSocket.getInputStream()); //notice inputStream and outputStream are created only once here, maybe that is the issue ?
outputStream = new ObjectOutputStream(clientSocket.getOutputStream());
while ( (message = (Message)inputStream.readObject() ) != null) {
if (message.type == Y) {
message.type = X ; //notice this is used in Client code
outputStream.writeObject(message);
outputStream.flush();
} else if (message.type == X ) {
// don't send anything to client, we are done processing this message
}
}
After looking around in google, I got some idea that ObjectInputStream and ObjectOutputStream must be somehow synchronized. But I did not get a concrete understanding. If someone can point out mistake in my code, it will be helpful.
Code flow :
- Client sends a message to server with message type Y, asking for information.
- Server sees the type Y, sets information in the object, changes message type to X, and replies to client.
- Client receives replies from all others. Note : There are 5 applications running both server and client. Hence the client will wait until it gets replies from all the others before proceeding.
Now client must send the received information to all 5 applications, and does that in replyToServer
method. The exception occurs there.
PS : This is pseudo code, and if any more details are required to understand code flow , please let me know in the comments.
Actual stack trace
err: java.io.StreamCorruptedException
err: at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1530)
err: at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1483)
.....`