java.io.StreamCorruptedException:无效的流标头

Var*_*man 2 java sockets

我正在编写一个套接字客户端,我将数据发送到服务器(使用getOutputStream()),下面是我的代码

 this.wr = this.socket.getOutputStream();

  wr.write(hexStringToByteArray(messageBody));

wr.flush(); 
Run Code Online (Sandbox Code Playgroud)

以上是成功的能够发送数据.1)但是当我尝试使用时读取响应

this.in = new ObjectInputStream(this.socket.getInputStream());
Run Code Online (Sandbox Code Playgroud)

因为我不知道服务器返回的格式.在这一行得到错误

"java.io.StreamCorruptedException:无效的流标题".

我不知道为什么?我知道我将收到的值将是十六进制格式,即600185将如同60 01 86 ....

任何人都可以帮助我,过来这个错误.

2)如果我在一定时间后没有收到任何响应,如何关闭套接字连接.

提前感谢你们.

MeB*_*Guy 5

ObjectInputStream期望由ObjectOutputStream写入的流中的标头.所以如果你使用一个,你需要使用它们.

由于您的示例并不真正需要ObjectOutputStream,您可能只是不想使用ObjectInputStream.

就像是:

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);
}
Run Code Online (Sandbox Code Playgroud)