【问题标题】:ObjectInputStream : StreamCorruptedException对象输入流:流损坏异常
【发布时间】:2012-03-22 10:54:27
【问题描述】:

大家好,我必须编写一个通过套接字连接进行通信的服务器。 客户端将对象发送到服务器,服务器将其打印到控制台。

public class ConnectionListener {

ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
Object message;

void runListener()
{
    try{
        providerSocket = new ServerSocket(2004, 10);
        System.out.println("Waiting for connection");
        connection = providerSocket.accept();
        System.out.println("Connection received from " + connection.getInetAddress().getHostName());
        in = new ObjectInputStream(connection.getInputStream());
        out = new ObjectOutputStream(connection.getOutputStream());
        do{
            message = in.readObject();
            System.out.println("client>" + message);
        }while(!message.equals("bye"));
    }
    catch(IOException ioException){
        ioException.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally{
        try{
            in.close();
            out.close();
            providerSocket.close();
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
    }
}

}

但我总是在这一行成为 StreamCorruptedException:

in = new ObjectInputStream(connection.getInputStream());

谁能帮帮我?

谢谢

【问题讨论】:

  • 连接的另一端可能正在向您发送错误数据。从您给我们的信息中无法确定。
  • 客户端通过连接发送什么? ObjectInputStream 需要一个序列化的 Java 对象。这是客户端发送的内容吗?
  • 你也可以发布发送方代码吗?
  • 我正在通过 telnet 连接到服务器并发送正常的文本输入。

标签: java


【解决方案1】:

我正在通过 telnet 连接到服务器并发送正常的文本输入。

所以另一端根本没有使用ObjectOutputStream,所以使用ObjectInputStream只是一派胡言。

如果您只想阅读文本,请使用BufferedReader.readLine()

【讨论】:

  • 好的,这意味着要测试这个服务器,我必须编写一个使用 Objectoutputstream 的客户端。对吗?
  • 正确。而当你这样做的时候,你需要创建ObjectOutputStreambeforeObjectInputStream,至少在一端。为了安全起见,在两端都这样做,那你就不会错。
猜你喜欢
  • 2016-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多