Open In App

How to Create a Socket at a Specific Port in Java?

Last Updated : 15 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. Socket Programming, us basically client-server programming where a socket is used as a link between them. We need to import the ‘java.net package in our program which provides two classes namely Socket class and ServerSocket class. Socket Class implements the client-side of the connection and ServerSocket class implements the server-side of the connection.

Procedure: 

In order to create a socket, the ‘java.net‘ package needs to be imported thereafter using the Socket and ServerSocket class, we create the object of that class.

  1. The Server opens a ServerSocket on a well-known port and waits for input.
  2. Meanwhile, the Client opens a (client) Socket with the server’s hostname and this well-known port address.
  3. It sends a request message to the server to initialize a communication session.

At Server Side

import java.net.Socket;
ServerSocket mySsocket= new ServerSocket(portnumber);

Note: The ServerSocket class takes a single parameter: Port number.  

Here, the ServerSocket is created by passing it a specific port number to listen on.

At Client Side

import java.net.Socket;
Socket myCsocket= new Socket( address, portnumber);

Note: The Socket class takes the two parameters namely Address and the Port number. 

This ask the server side for the IP address, and then it opens a socket to that server on that specified port.

Example 1: Server-side 

Java




// Java program for creating socket on Server-side
// Server program depicting creation of a socket
// at a specific port
 
// Importing majorly Socket and ServerSocket class
// from java.net package
import java.net.*;
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args) throws Exception
    {
 
        // Try block to check for exceptions
        try {
 
            // Creating an object of ServerSocket class
            // with the custom port number - 80
            ServerSocket mySsocket = new ServerSocket(80);
 
            // Display commands for better readability
            System.out.println("Server started");
            System.out.println("Waiting for a client ...");
 
            // Here it will wait for any client which wants
            // to get connected to this server
 
            // Establishing a connection
            // using accept() method()
            Socket socket = mySsocket.accept();
 
            // Display message
            System.out.println(
                "Client accepted through the port number: "
                + mySsocket.getLocalPort());
 
            // getLocalPort() function returning the port
            // number which is being used
        }
 
        // Catch block to handle for exceptions
        catch (Exception e) {
 
            // Simply return/exit
            return;
        }
    }
}


 Output:

Server started
Waiting for a client ...
Client accepted through the port number: 80

Example 2: Client-side

Java




// Java program for creating socket on Client-side
// Client program depicting creation of a socket
// at a specific port
 
// Importing majorly Socket and ServerSocket class
// from java.net package
import java.net.*;
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args) throws Exception
    {
 
        // Try block to check for exceptions
        try {
 
            // Creating an object of Socket class where
            // port number same as server side program
            Socket myCsocket = new Socket("localhost", 80);
 
            // creating client with local ip address
            // port number as '80'
 
            // Display message for better readability
            System.out.println("Connected to Server");
        }
 
        // Catch block to handle exceptions
        catch (Exception e) {
 
            // Simply return and exit the program
            return;
        }
    }
}


Output:

Connected to Server

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads