java - 对象输入流 : StreamCorruptedException

标签 java

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

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

有人可以帮我吗?

谢谢

最佳答案

I´m connecting to the server via telnet and sending normal text input.

所以另一端根本没有使用ObjectOutputStream,所以使用ObjectInputStream只是废话。

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

关于java - 对象输入流 : StreamCorruptedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59948949/

相关文章:

java - 从多个源 DTO 映射到一个目标

java - 在 Spring Batch 中生成多个异步作业后如何使主线程保持等待状态

java - 修复这些 boolean 值的简单方法是什么?

java - 以ip地址样式打印字符串

java - 将 java.util.Date 转换为 json 格式

Java Split 取出单个单词并将它们保存为字符串?

java - 如何从 Instant.now() 获取 DayOfWeek

java - 找不到符号textView AndroidStudio

java - 在heroku上部署而不保留gradlew文件

java - 当输入中存在不同形式的参数时分割字符串