简体   繁体   中英

Java socket output stream

Can you have an PrintWriter and ObjectOutputStream on the same sockets output stream?

out_stream = new PrintWriter(socket.getOutputStream(), true);
obj_stream = new ObjectOutputStream(socket.getOutputStream();

I would say yes but I don't think I would do it.

What is it you want to do?

You can but you have to take care of buffering. A PrintWriter or an ObjectOutputStream accepts data, which it converts into bytes, to be sent on the underlying stream (here the socket) at some point . Buffering is about waiting a bit before writing out such bytes, so that the bytes can be sent in "big chunks" rather than individually.

Read the Javadoc about buffering, and use flush() on PrintWriter and ObjectOutputStream when you want to get sure that the bytes get written on the socket.

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