Table of contents
1.
Introduction
2.
Methods of Server Socket Class
2.1.
The bind() method
2.2.
The accept() method
2.3.
The getLocalPort() method
2.4.
The getInetAddress() method
2.5.
The close() method
3.
Example Program
3.1.
Client-Side Program
3.2.
Server Side Program
4.
Steps to run the program and final output
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Server Socket Class in Java

Author Vasu Bansal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will discuss about Server Socket class in Java. Socket programming is an exciting concept in Computer Science. It helps multiple client programs to connect and exchange information with the server. The implementation that uses Java's server socket class has many advantages. One of them is that the program becomes independent of the system on which it is running. 

Must Read, Multithreading in java, Duck Number in Java

Methods of Server Socket Class

There are a lot of methods present in the Server Socket Class in Java. Some of them are discussed below.

The bind() method

Before using the socket, we must bind it to a specific address. This can be achieved with the help of the bind() method. The address is defined by the combination of IP Address and Port number.

The accept() method

The accept method makes a blocking call by waiting for the incoming connections on this socket. It is used to accept incoming connections.

The getLocalPort() method

This method is used to find the local port number on which the socket in discussion is running.

The getInetAddress() method

This function returns the local address of the server socket.

The close() method

This method plays a very crucial role in creating programs involving Server Socket Class in Java. It is used to close the socket. It is essential to close the socket so that it can be used again for other purposes.

Example Program

In this section, we will look at a sample program containing a client and a server. In this program, the client and server establish a connection, and upon successful connection, they exchange a message between them.

Client-Side Program

The following is the program for the Client.java file.

Code:

// Java Client Side Program
import java.io.*;
import java.net.*;

public class Client {

    public static void main(String[] args){
        try {
            System.out.println("Client program started");

            int PORT = 9000;
           
            String IP = "127.0.0.1";

            Socket conn = new Socket(IP, PORT);

            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
           
            String mssge = "Hello Ninja";

            dos.writeUTF(mssge);

            System.out.println("Client sent the message: " + mssge);

            dos.flush();
       
            dos.close();

            conn.close();

            System.out.println("Client program closed");
        }
        catch (Exception exp) {
            System.out.println(exp);
        }
    }
}

Server Side Program

The following is the program for the Server.java file.

Code:

// Java Server Side Program

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

public class Server {
    public static void main(String[] args){
        try {
            System.out.println("Starting the server");

            int PORT = 9000;

            ServerSocket sock = new ServerSocket(PORT);

            Socket conn = sock.accept();

            System.out.println("Client Server Connection established");

            DataInputStream dis = new DataInputStream(conn.getInputStream());

            System.out.println("Waiting for the client's message");

            String msg = (String)dis.readUTF();

            System.out.println("Message from client : " + msg);

            conn.close();

            sock.close();

            System.out.println("Closing the server");
        }
        catch (Exception exp) {
            System.out.println(exp);
        }
    }
}


Practice by yourself on java online compiler.

Steps to run the program and final output

You need to have java installed in your system to run this program.  The first step is to run the server. Use the following commands to run the server. 

> javac Server.java

> java Server

After running the server, open another terminal and run the client using the following commands.

> javac Client.java 

> java Client

After running the client, you will see the following output on the server terminal.

Also read, Hashcode Method in Java

FAQs

  1. What is the use of setReuseAddress() function in Java Socket programming?
    Ans: This function is used to disable or enable the option of SO_REUSEADDR socket. 
     
  2. How can I get the local port number on which the socket is listening?
    Ans: You can get the local port number on which the socket is listening by calling the function getLocalPort().
     
  3. Why is it important to close the sockets connections after the program ends?
    Ans: It is important to close the socket connections after the program ends because if the socket is not closed, it will not allow any other socket to bind to the same. The socket can be closed with the help of close() function.

Key Takeaways

In this blog, we have extensively discussed the Server Socket Class in Java and understood its implementation. Also, read the blog, Writer class in Java to learn this interesting and exciting concept.

Check out this article - Upcasting and Downcasting in Java

If you want to learn more, check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass