. io .StreamCorruptedException:无效的头

时间:2021-12-20 20:31:13

I am writing a socket client in which I am sending data to server (using getOutputStream()),below is my code

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

 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

以上是成功地发送数据。1)但是当我尝试使用

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" .

“io。流标题无效。

I am not sure why ? I know the values that I will recieve will be in the hex format i.e say 600185 would be as in 60 01 86 ....

我不知道为什么?我知道我要接收的值将是十六进制格式I。e说600185将在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.

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

Thanking you all in advance.

提前感谢大家。

1 个解决方案

#1


5  

ObjectInputStream expects a header in the stream that is written by ObjectOutputStream. So If you use one, you need to use both.

ObjectInputStream需要一个由ObjectOutputStream编写的流头。所以如果你用一个,你需要同时用两个。

As your sample doesn't really need ObjectOutputStream, you may just want to not use ObjectInputStream.

由于您的示例并不真正需要ObjectOutputStream,您可能只想不使用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);
}

#1


5  

ObjectInputStream expects a header in the stream that is written by ObjectOutputStream. So If you use one, you need to use both.

ObjectInputStream需要一个由ObjectOutputStream编写的流头。所以如果你用一个,你需要同时用两个。

As your sample doesn't really need ObjectOutputStream, you may just want to not use ObjectInputStream.

由于您的示例并不真正需要ObjectOutputStream,您可能只想不使用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);
}