java.io.StreamCorruptedException: invalid stream header: 00000001

此生再无相见时 提交于 2019-12-29 08:23:14

问题


I keep getting this get this Exception:

java.io.StreamCorruptedException: invalid stream header: 00000001

Server side I used this to send and receive int, works fine.

Server:

new DataOutputStream(player1.getOutputStream()).writeInt(P1);

Client:

dataFromServer = new DataInputStream(socket.getInputStream());
dataFromServer.readInt();

But when I try to send an object, like this, it gives the error.

Server:

new ObjectOutputStream(player2.getOutputStream()).writeObject(gameCrossword);

Client:

objectFromServer = new ObjectInputStream(socket.getInputStream());
crossword = (Crossword)objectFromServer.readObject();

Any help would be good. Here is me sending the crossword initially prior to game session

I changed the code to use only object streams rather than data streams, upon the advice of jtahlborn

server

player1 = serverSocket.accept();

serverLog.append(new Date() + ": Player 1 joined session " + sessionNo + '\n');
serverLog.append("Player 1's IP address" + player1.getInetAddress().getHostAddress() + '\n');

new ObjectOutputStream(player1.getOutputStream()).writeInt(P1);
new ObjectOutputStream(player1.getOutputStream()).writeObject(gameCrossword);

player2 = serverSocket.accept();

serverLog.append(new Date() + ": Player 2 joined session " + sessionNo + '\n');

serverLog.append("Player 2's IP address" + player2.getInetAddress().getHostAddress() + '\n');

new ObjectOutputStream(player2.getOutputStream()).writeInt(P2);
new ObjectOutputStream(player2.getOutputStream()).writeObject(gameCrossword);

client

              private void connectToServer() {

    try {
        Socket socket = new Socket(host, 8000);
        objectFromServer = new ObjectInputStream(socket.getInputStream());
        objectToServer = new ObjectOutputStream(socket.getOutputStream());

    } catch (IOException ex) {
        System.err.println(ex);
    }

    Thread thread = new Thread(this);
    thread.start();
}

@Override
public void run() {

    try {
        player = objectFromServer.readInt();
        crossword = (Crossword)objectFromServer.readObject();
        System.out.println(crossword);

regards, C.


回答1:


don't wrap the socket streams with more than one input/output streams. this will break in all kinds of bad ways. in this specific case, the ObjectInputStream reads a header from the stream on construction, which is happening before you have read the int from the stream. regardless, just use a single ObjectOutputStream and ObjectInputStream and ditch the Data streams (note that ObjectOutputStream has a writeInt method).



来源:https://stackoverflow.com/questions/20773657/java-io-streamcorruptedexception-invalid-stream-header-00000001

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!