How to Write Data to a Socket Using Java


In this article, we show how to write data to a socket using Java.

To connect to another machine, we need a Socket connection.

A Socket is an object that represents a network connection between 2 machines. So that the 2 pieces of software know about each other and are able to communicate with one another.

When referencing Socket connections, usually one machine is the server and the other machine is the client. The client is the machine connecting to and communicating with the server. In exchange, the server sends information back to the client.

To make a Socket connection, you need to know 2 things about the server, its network location (IP address) and what port it is running on.

So once the 2 machines know each other's network location and port number, they can communicate with each other.

To communicate over a Socket connection, you use PrintWriter class.

This is shown in the code below.

So in the above code, we import the package because this has the PrintWriter class. We also must import the package, which contains the Socket class.

We create a public class named Writesocket.

Underneath this class declaration, we create the main method, which is where our program executes.

In this method, we use exception handling using try and catch statements.

We create a Socket object from the Socket class. Inside of this Socket object, we declare the IP address and the port number of the server we are referencing. In the code above, the IP address is and the port number is 4242.

Next, we create an instance of the PrinterWriter class named writer. Inside the parameter of this PrintWriter object, we pass in the value sock.getOutputStream(). This establishes an output stream for this sock object. This enables us to get able to write out data to the socket. that we've created.

Then, to actually write out data, we take the object, write, and follow it with the println() or print() function and write anything that we want to the socket.

When you are done writing data to the socket, you must close the connection to the socket. Or else, the data won't be written.

We have a catch statement for the reason of exception handling.

So this is how we can write data to a socket using Java.

Related Resources

How to Read Data from a Socket Using Java

HTML Comment Box is loading comments...