How to Create a Socket at a Specific Port in Java?
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.
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
Server started Waiting for a client ... Client accepted through the port number: 80
Example 2: Client-side
Connected to Server