Saturday, January 25, 2020

Socket and ServerSocket classes

Socket class

A Socket is the endpoint of a bidirectional communication link established between two Applications running on a network. The socket is bound to a port number which is a 2-byte unsigned integer value and its range varies from 0 to 65535.  TCP layer can identify the service by which data is going to be sent by this port number. Port numbers 0- 1023 are reserved for standard services. We can create and develop our own service on any port number 1024 to 65535. An endpoint of communication can be considered as a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its Port number and IP Address. The java.net package in the Java Platform provides us Socket class which is the implementation of one side of the two way communication over the network.

Socket port number and services


ServerSocket Class

ServerSocket class object keeps listening on a dedicated port for a request over the network from the client-side. Whenever a request is received, we can fetch the request accordingly and possibly return some response to the client. A client is a program that will send a request to the server. We can write a response back using a Socket at the server-side. A server is a program having the capacity to serve the response back to the client. ServerScoket class implements Closeable interface.

client-server

client-server

ExampleClient program


import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class Client {//Client
public static void main(String[] args) {
System.out.println("Welcome,i am client program");
Scanner scan=new Scanner(System.in);
System.out.println("Enter y to see date and time");
String y=scan.next();
if(y.equals("y"))
{
System.out.println("you send request");
try {
Socket socket=new Socket("localhost", 5545);//Socket is open to send request
DataInputStream dis=new DataInputStream(socket.getInputStream());
String date=dis.readLine();
System.out.println(date);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Server program


import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class Server {//Server

public static void main(String[] args) {
Socket socket;
System.out.println("Server is up");
ServerSocket ss;
while(true)
{
try {
System.out.println("Sending...");
ss=new ServerSocket(5545,5);//port number and backlogs no of clients those can queue
socket=ss.accept();
DataOutputStream dos=new DataOutputStream(socket.getOutputStream());
dos.writeBytes("Date is "+ (new Date()).toString());
dos.close();//Close streams and sockets
ss.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}

                }
}
}


Video Tutorial