How to Read Data From a Socket Using Java 


               


How to Read Data from a Socket Using Java

Java


In this article, we show how to read data from 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 streams.

This is shown in the code below.



So in the above code, we import the java.io package because this has the InputStreamReader and BufferedReader definitions. We also must import the java.net package, which contains the Socket class.

We create a public class named ReadSocket.

In this class, we create our 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 127.0.0.1 and the port number is 4242.

Next, we create an instance of the InputStreamReader class named streamReader. We pass in the parameter, sock.getInputStream(). This gets the input stream of the socket object that we've created.

We then create a BufferedReader object named reader and pass in the parameter, streamReader. This ties in the input stream from the socket object we've created to the BufferedReader class so that we can read the data from the socket.

We then create a variable named value and set it equal to reader.readLine(). This reads in the value from the BufferedReader object, reader.

We then output the value and close the BufferedReader object once done.

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

And this is all that is necessary to read a socket using Java.


Related Resources

How to Write Data to a Socket Using Java




HTML Comment Box is loading comments...