Can not read number send with DataOutputStream

不羁岁月 提交于 2019-12-20 07:26:11

问题


this is my Client code

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

and this is the Server code

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

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

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

i don't got result


回答1:


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.)

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.

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




回答2:


If you're using writeInt() on the write side, you should be using readInt() on the read side (all the method names correlate between DataOutputStream and DataInputStream, please read the javadoc).



来源:https://stackoverflow.com/questions/16303802/can-not-read-number-send-with-dataoutputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!