How to Create a Socket at a Specific Port in Java?
Last Updated :
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.
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
import java.net.*;
public class GFG {
public static void main(String[] args) throws Exception
{
try {
ServerSocket mySsocket = new ServerSocket( 80 );
System.out.println( "Server started" );
System.out.println( "Waiting for a client ..." );
Socket socket = mySsocket.accept();
System.out.println(
"Client accepted through the port number: "
+ mySsocket.getLocalPort());
}
catch (Exception e) {
return ;
}
}
}
|
Output:
Server started
Waiting for a client ...
Client accepted through the port number: 80
Example 2: Client-side
Java
import java.net.*;
public class GFG {
public static void main(String[] args) throws Exception
{
try {
Socket myCsocket = new Socket( "localhost" , 80 );
System.out.println( "Connected to Server" );
}
catch (Exception e) {
return ;
}
}
}
|
Output:
Connected to Server
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...