简体   繁体   中英

Can not read number send with DataOutputStream

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

如果在写端使用writeInt() ,则应在读端使用readInt() (所有方法名称在DataOutputStream和DataInputStream之间相关,请阅读javadoc)。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM