本文介绍了无法读取通过DataOutputStream发送的号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的客户代码

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

这是服务器代码

try {
     DataInputStream dis = new DataInputStream(socket.getInputStream());
     BufferedReader input = new BufferedReader(new InputStreamReader(dis));
     int fromClient = input.read();
     System.out.println(fromClient);
} catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
}

但是即使我喜欢修改fromClient,我也不接受任何内容

But i don't recive anything in fromClient , even if i chnage it like this

System.out.println(fromClient+"test");

我没有结果

推荐答案

客户端需要调用 dos.flush() dos.close()导致将缓冲的数据推入服务器。 (如果打算写入更多数据,则刷新,否则关闭。)

The client needs to either call dos.flush() or dos.close() to cause buffered data to be pushed to the server. (If you intend to write more data, then flush, otherwise close.)

服务器端需要使用 DataInputStream上的readInt读取数据。 实例。使用DataOutputStream写入的数据应该使用DataInputStream读取。

The server side needs to read the data using readInt on the DataInputStream instance. Data that is written using a DataOutputStream should be read using a DataInputStream.

最后,摆脱BufferedReader / InputStreamReader。只是错了。

Finally, get rid of BufferedReader/InputStreamReader. It is just wrong.

这篇关于无法读取通过DataOutputStream发送的号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 13:16
查看更多