Java – Networking using Sockets

What is Networking?

Networking in Java, is the concept of establishing a connection between two computing devices, the Client and the Server, that are running on two different JREs. This connection gets established at the TCP layer.

There can be n number of Clients that interact with the Server. Networking provides the sharing of data and resources among the Clients. Communication between the Client and the Server can be either connection-oriented or Connectionless.

Sockets

The communication between the Client and the Server is achieved using Sockets. For connection-oriented communication, we use Socket and ServerSocket classes and for connectionless communication, we use DatagramSocket and DatagramPacket classes. These Socket classes are available in the java.net.Socket package.

Every Client needs a socket at its end to connect to the Server. And for every Client, the Server requires one socket each at its end to connect with the Clients.

So, every time a Client sends a connection request to the Server, the ServerSocket is responsible to accept the request and allot a dedicated socket at the server-side to the Client.

While sending the connection request to the Server, the Client should require to know two things:

  • The IP address of the Server and
  • The Port number of the application that is running on the Server.

The Socket Class

The Socket class is used on the Client-side to create a Socket and send a connection request to the Server. The Syntax for creating a Socket object is shown below:

Socket s = new Socket(“ip_address”, port_number);

The ip_address is the IP Address of the Server. The port_number can range between 0 and 65,535. But, the port number between 1 and 1023 are reserved and can’t be used. There can also be some port numbers that can be in use by other applications on your system. So, it’s possible to encounter an error while working with such port numbers. So, it’s required that you specify a unique port_number while sending the connection request to the Server.

Every server has a unique IP address. There can be many applications or processes running on a Server and every application has a dedicated Port number to it.

There are two streams that come attached with the Socket. The InputStream and the OutputStream. The data that needs to be received by the Socket will be sent to the Socket’s InputStream. The data that needs to be sent through the Socket will be sent to the Socket’s OutputStream.

Methods of the Socket class

Let’s see the methods of this class;

As mentioned above, Socket class is used to connect to the sever from client-side. So, it has connect method for this. This method opens the communication connection between client & server. Which server? We need to pass it through it’s argument. The syntax looks like below;

void connect(SocketAddress host, int timeout)

host is the server address the socket connects to. timeout is useful parameter here, mentioned in milliseconds, used to connects the socket with the server, specified milliseconds.

InetAddress getInetAddress() & int getPort() methods are useful to returns the address of the remote system & the port number the socket connects to.

The data transfer between client and server over the network is though Streams. getInputStream() & getOutputStream() methods are useful to return the InputStream & OutputStream objects respectively.

Once done with connection, we can close the communication between client & server using it’s close() method.

The ServerSocket class

In client-server communication, Socket class we use from client side. And ServerSocket class we use from server side. Every time a client sends a connection request, it helps in accepting or rejecting the request. Only after the ServerSocket accepts the request, the connection between the client and the server will establish. After accepting the connection request, the ServerSocket returns an object of the Socket class. This Socket object helps in transmitting the data.

Syntax to create the ServerSocket object:

ServerSocket ss = new ServerSocket(“port_number”);

Clients sending the connection requests with this mentioned, port_number will be accepted by the server to establish a connection.

Syntax to create the Socket object on server-side:

Socket s = ss.accept();

The accept() method accepts the connection requests and returns a newly created Socket object.

Methods of the ServerSocket class

accept() method is used to complete the connection establishment, between client & the server. It returns Socket object. close() method is used close the socket.

Once the connection is established, we can send and receive data between the Client and the Server.

It’s time to write the code

Let’s see how we can establish the socket communication with an example;

Step 1. We need to have two programs; one act like a server and another one act like a client.

Step 2. Run the server program first. This will wait for the connections from the client.

Step 3. Run the client program, next. This will establish the socket connection between client & server.

Let’s see these programs;

The Server Class

package com.codesteps.server;

import java.io.*;
import java.net.*;

public class ServerSoc {
    public static void main(String args[]) throws Exception {
        System.out.println("Server Starting");
        ServerSocket ss = new ServerSocket(9999); // ServerSocket for accepting requests 
        System.out.println("Waiting for Client's request");
        Socket s = ss.accept(); // establishing connection
        System.out.println("Client Connected");

        DataInputStream in = new DataInputStream(s.getInputStream());
        String str = in.readUTF(); // reading from the i/p stream
        System.out.println("Message received from Client: " + str);

        in.close();
        ss.close();
        s.close();
    }
}

Run the program and observe that, below output will be displayed on the console;

Server Starting
Waiting for Client's request

Now, the server is running and waiting for the requests from the client. Then, we will look at client class.

The Client Class

package com.codesteps.client;
import java.io.*;
import java.net.*;

public class ClientSoc {
    public static void main(String args[]) throws Exception {
        String ip_address = "localhost"; //since the server program is on the same machine
        int port = 9999;
        Socket s = new Socket(ip_address, port);
        String str = "Welcome to CodeSteps";
        DataOutputStream out = new DataOutputStream(s.getOutputStream()); // returns the o/p stream attached with the Socket
        out.writeUTF(str); // writing data to o/p stream
        out.flush(); // flushing the o/p stream

        out.close();
        s.close();
    }
}

After running this program, client will be connected to the server. As already server is waiting for the requests from the client; below output will be displayed on the server console;

Client Connected
Message received from Client: Welcome to CodeSteps

Code walkthrough

On the Server side, we require two Sockets. One is the ServerSocket for accepting requests from Clients. It accepts the Client requests that contain the specified port number. The other one is the Socket object that helps in establishing a connection with the Client.

Here we are using the DataInputStream object to read the data. The data sent by the Client will be read by the server.

The Client class requires a Socket to connect to the server and therefore, we create a Socket with the IP Address of the Server. It is localhost in this case, as the server is also run from the same system. The port number describes the application on the server that it wants to connect with.

The s.getOutputStream() method returns the o/p stream attached to the Socket. This is stored into the DataOutputStream object.

After writing the data to the output stream we flush the output stream. This is to make sure our entire data gets written to the i/p stream of the Socket on the server-side.

Here we are using the DataOutputStream to output the data. This will be read by the server.

Now, we have successfully complete our client-server communication, using sockets.

We will discuss more topics in upcoming articles. Do not forget to give the feedback, in below comments section.

Add a Comment

Your email address will not be published.