Socket
Write text to Socket
In this example we shall show you how to write text to a Socket. To write text to a Socket one should perform the following steps:
- Get the output stream of the socket, using
getOutputStream()
API method of Socket. - Create an OutputStreamWriter with the socket ouputstream.
- Create a BufferedWriter that uses a default-sized output buffer.
- Use
write(String str)
API method to write the text andflush()
API method to flush the stream. - Don’t forget to close the BufferedWriter, using the
close()
API method,
as described in the code snippet below.
try { BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); wr.write("Data to be sent"); wr.flush(); wr.close(); } catch (IOException ioe) { System.out.println("I/O Error " + ioe.getMessage()); }
This was an example of how to write text to a Socket in Java.