将InputStreamReader与Java一起使用时出错

时间:2013-04-30 16:15:57

标签: java objectinputstream

我尝试从客户端向服务器发送一个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);
}

但是我收到了无效的流标头错误。

  

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

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

2 个答案:

答案 0 :(得分:1)

您使用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:你不是在读它,因为这看起来像是二进制数据的流,所以将它当作文本处理是不合适的

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

答案 1 :(得分:0)

尝试像这样改变它

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

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