java.io.StreamCorruptedException: invalid stream h

2019-01-27 09:44发布

问题:

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