重用ObjectInputStream会引发StreamCorruptedException

时间:2015-03-06 13:56:37

标签: java sockets networking inputstream outputstream

我有一个客户端 - 服务器应用程序。客户端发送对象并且服务器发回同一对象的地方,一个简单的echo服务器。如果我为每个新请求创建Client的新实例,则下面的代码工作正常。但是,如果我使用客户端的现有实例,则会为我提供java.io.StreamCorruptedExceptionjava.lang.ClassCastException

客户端

Socket socket = new Socket(hostName, port);


in = new ObjectInputStream(
            new BufferedInputStream(socket.getInputStream()));
out = new ObjectOutputStream(socket.getOutputStream());

//calling this each time I have a new request
out.writeObject(request);
out.flush();
Object object = in.readObject();

服务器

ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
new Thread(new ClientWorker(clientSocket)).start();

ClientWorker

public void run() {
        try {
            ObjectOutputStream out =
                    new        ObjectOutputStream(clientSocket.getOutputStream());

            ObjectInputStream in = new ObjectInputStream(
                    new BufferedInputStream(clientSocket.getInputStream()));

            Object inputObject;

      while(true) {
            while ((inputObject = in.readObject()) != null) {
                  out.writeObject(inputObject);
            }

            out.flush();
        }
    } catch (IOException e) {
            e.printStackTrace();
    } catch (ClassNotFoundException e) {
            e.printStackTrace();
    }
}

编辑:

在重用的客户端

中执行以下代码时

in.readObject();

我得到了例外

  

java.io.StreamCorruptedException:无效的类型代码:00 at   java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1497)     在   java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1748)     at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1327)     在java.io.ObjectInputStream.readObject(ObjectInputStream.java:349)

1 个答案:

答案 0 :(得分:0)

在我对输入和输出对象流进行同步后问题得以解决。

synchronized(this) {
    while ((inputObject = in.readObject()) != null) {
        out.writeObject(inputObject);
    }
}

synchronized(this) {
   out.writeObject(request);
   out.flush();
   Object object = in.readObject();
}