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

15 Sep, 2021
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.
The Server opens a ServerSocket on a well-known port and waits for input.Meanwhile, the Client opens a (client) Socket with the server’s hostname and this well-known port address.It sends a request message to the server to initialize a communication session.
The Server opens a ServerSocket on a well-known port and waits for input.
Meanwhile, the Client opens a (client) Socket with the server’s hostname and this well-known port address.
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 packageimport java.net.*; // Classpublic 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 packageimport java.net.*; // Classpublic 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
 
simranarora5sos
Java-Networking
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java