I'm still relatively new to sockets, and I haven't seen any information regarding this subject.
To write to a connected socket, you can either use
socket.getOutputStream().write
Or create a new DataOutputStream
from the socket OutputStream
and write to that.
A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.
In Java, to send data via the socket, you get an OutputStream (1) from it, and write to the OutputStream (you output some data). To read data from the socket, you get its InputStream , and read input from this second stream. You can think of the streams as a pair of one-way pipes connected to a socket on the wall.
public class DataInputStream extends FilterInputStream implements DataInput. A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.
The getOutputStream() method of Java Socket class returns an output stream for the given socket. If you close the returned OutputStream then it will close the linked socket.
DataOutputStream
makes sure the data is formatted in a platform independent way. This is the big benefit. It makes sure the party on the other side will be able to read it. There is no significant performance difference between both.
You should use OutputStream
only if you transfer raw binary data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With