将InputStreamReader与Java一起使用时出错

我试图从客户端向服务器发送一个int值 . 这是我在下面使用的客户端代码:

_port   = 8071;
_socket = new Socket("localhost", _port);

Random rand = new Random();
int  n = rand.nextInt(50) + 1;
DataOutputStream dos = new DataOutputStream(_socket.getOutputStream());
dos.writeInt(n);
dos.flush();

服务器代码

try {
    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    ObjectInputStream in = null;
    in = new ObjectInputStream(socket.getInputStream());
    int ClientNumber= in.readInt();
    System.out.println(ClientNumber);
}

但我收到一个无效的流 Headers 错误 .

无效流头:0000002B在java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:781)在java.io.ObjectInputStream中(ObjectInputStream.java:278)在ServiceRequest.run(ServiceRequest.java:24)在java.util中.concurrent.Executors $ RunnableAdapter.call(Executors.java:439)在java.util.concurrent.FutureTask中$ Sync.innerRun(FutureTask.java:303)在java.util.concurrent.FutureTask.run(FutureTask.java:138 )在java.util.concurrent.ThreadPoolExecutor中$ Worker.runTask(ThreadPoolExecutor.java:895)在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:918)在java.lang.Thread.run(线程 . Java的:680)

有谁知道导致错误的原因是什么?我的代码设置不正确吗?

回答(2)

2 years ago

你正在使用 DataOutputStream 并使用 ObjectInputStream 进行阅读 . 您应该使用DataInputStream代替:

// Note declaration and assignment in a single statement. There's no point in
// making it null first.
DataInputStream in = new DataInputStream(socket.getInputStream());

// Note use of camelCase for variable name
int clientNumber = in.readInt();

你也应该摆脱 input :你're not reading from it, and as this looks like it'是一个二进制数据流,将它当作文本处理是不合适的 .

哦,你应该在 finally 块中关闭输入流 .

2 years ago

试着像这样改变它

try {
             //   input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            DataInputStream in = new DataInputStream(socket.getInputStream());
            int clientNumber= in.readInt();
            System.out.println(clientNumber);
}

它应该工作 . ObjectInputStream只能读取ObjectOuputStream发送的流,它以幻数(header) 0xACED 开头,参见http://docs.oracle.com/javase/6/docs/platform/serialization/spec/protocol.html