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

时间:2013-12-25 14:15:01

标签: java exception file-io multiplayer

我一直得到这个Exception

java.io.StreamCorruptedException: invalid stream header: 00000001

服务器端我用它来发送和接收int,工作正常。

服务器:

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

客户端:

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

但是当我尝试发送一个像这样的对象时,它会给出错误。

服务器:

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

客户端:

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

任何帮助都会很好。这是我最初在游戏会话之前发送填字游戏

根据jtahlborn的建议,我将代码更改为仅使用对象流而不是数据流

服务器

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

客户端

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

的问候, 下进行。

1 个答案:

答案 0 :(得分:3)

不要使用多个输入/输出流包装套接字流。这将以各种不好的方式打破。在这种特定情况下,ObjectInputStream从构造上的流中读取一个头,这是在您从流中读取int之前发生的。无论如何,只需使用一个ObjectOutputStream和ObjectInputStream并抛弃数据流(请注意,ObjectOutputStream具有writeInt方法)。