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
1 import java.net.Socket;
2 ServerSocket mySsocket= new ServerSocket(portnumber);
At client side
1 import java.net.Socket;
2 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.
1 package com.java;
2
3 import java.net.ServerSocket;
4 import java.net.Socket;
5
6 public class Example {
7
8 public static void main(String[] args) {
9
10 try {
11 ServerSocket mySsocket = new ServerSocket(80);
12
13 System.out.println("Server started");
14 System.out.println("Waiting for a client ...");
15
16 Socket socket = mySsocket.accept();
17 System.out.println("Client accepted through the port number: "
18 + mySsocket.getLocalPort());
19 } catch (Exception e) {
20 System.out.println("Exception : " + e.getMessage());
21 }
22 }
23 }
In the above example, a ServerSocket instance created by passing a port number. A socket class accept() method called that allows client program to connect to the server. An operation on client request can be perform using socket object.
1 Server started
2 Waiting for a client ...
3 Client accepted through the port number: 80
Client with port
1 package com.example;
2
3 import java.net.Socket;
4
5 public class Example {
6
7 public static void main(String[] args) throws Exception {
8
9 try {
10 Socket myCsocket = new Socket("localhost", 80);
11 System.out.println("Connected to Server");
12 } catch (Exception e) {
13 return;
14 }
15 }
16 }
In the above example, a Socket object is created by specifying a hostname and port where a server is running. A socket operation can be performed and send request to server using socket object.
Note : Once the connection between client and server established a program gets terminated.
Related options for your search