java.io.StreamCorruptedException: invalid stream header
I am writing a socket client in which I am sending data to server (using getOutputStream()),below is my code
this.wr = this.socket.getOutputStream();
wr.write(hexStringToByteArray(messageBody));
wr.flush();
The above is successfull able to send the data. 1) but when I try to read the response using
this.in = new ObjectInputStream(this.socket.getInputStream());
As I dont know what format the server is returning. Getting error at this line
"java.io.StreamCorruptedException: invalid stream header" .
I am not sure why ? I know the values that I will reci开发者_Go百科eve will be in the hex format i.e say 600185 would be as in 60 01 86 ....
Could any one please help me, to over come this error.
2) Also in case if I dont receive any response after certain duration, how to close the socket connection.
Thanking you all in advance.
ObjectInputStream expects a header in the stream that is written by ObjectOutputStream. So If you use one, you need to use both.
As your sample doesn't really need ObjectOutputStream, you may just want to not use ObjectInputStream.
something like:
public void doWrite(Socket socket, String messageBody) {
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
byte[] data = hexStringToByteArray(messageBody);
dos.writeInt(data.length);
dos.write(data);
dos.flush();
}
public String doRead(Socket socket) throws IOException {
DataInputStream dis = new DataInputStream(socket.getInputStream());
int len = dis.readInt();
byte[] data = new byte[len];
dis.read(data);
return byteArrayToHexString(data);
}
精彩评论