Simplified : Client_Server - Socket Programming in Java

Client_Server - Socket Programming in Java

java socket programming



Client -server communication

At a basic level, network-based systems consist of a server , client , and a media for communication. A computer running a program that makes a request for services is called client  machine. A computer running a program that offers requested services from one or more clients is called  server machine.

Client-Server Architcture


What are Sockets?

In Client-Server architecture, you have two processes (running client-Server programs) that want to communicate with each other. For that, they have to establish a communication link between themselves. There is a network available,they just need to connect to this network , for this they use sockets.

Sockets in client server architecture



A socket is one endpoint of a two-way communication link between two programs running on the network.


An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints. That way you can have multiple connections between your host and the server.
The java.net package in the Java platform provides a class, Socket, that implements one side of a two-way connection between your Java program and another program on the network. 

How do I Open a Socket ?

If you are programming a client, then you would open a socket like this:
 Socket s;
    s = new Socket("Machine name", PortNumber);
Where Machine name is the machine you are trying to open a connection to, and Port-Number is the port (a number) on which the server you are trying to connect to is running. When selecting a port number, you should note that port numbers between 0 and 1,023 are reserved for privileged users (that is, super user or root). These port numbers are reserved for standard services, such as email, FTP, and HTTP. When selecting a port number for your server, select one that is greater than 1,023!

It is a good practice to handle exceptions. The above can be written as:
    Socket s;
    try {
           s = new Socket("Machine name", PortNumber);
    }
    catch (IOException e) {
        System.out.println(e);
    }
If you are programming a server, then this is how you open a socket:
    ServerSocket ss;
    try {
       ss = new ServerSocket(PortNumber);
        }
        catch (IOException e) {
           System.out.println(e);
        }
When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients.
Socket clientSocket = null;
    try {
       serviceSocket = ss.accept();
        }
    catch (IOException e) {
       System.out.println(e);
    }

How do I create Buffered Reader?

Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by line by readLine() method. It makes the performance fast. 
    try {
      BufferedReader br = new BufferedReader(new InputStreamReader(ss.getInputStream()));
    }
    catch (IOException e) {
       System.out.println(e);
    }

How do I create an output stream?

On the client side, you can create an output stream to send information to the server socket using the class  of java.io:
    PrintStream output;
    try {
     OutputStream ostream = sock.getOutputStream();                 
     DataOutputStream dos = new DataOutputStream(ostream);
    }
    catch (IOException e) {
       System.out.println(e);
    }
The class DataOutputStream allows you to write Java primitive data types; many of its methods write a single Java primitive type to the output stream. The method writeBytes is a useful one.

How do I Close a Socket ?

On the client side:

    try {
           output.close();
           input.close();
           s .close();
    } 
    catch (IOException e) {
       System.out.println(e);
    }

On the server side:

    try {
       output.close();
       input.close();
       ss.close();
    } 
    catch (IOException e) {
       System.out.println(e);
    }
Let's see java code for one-way communication using socket programming:

Client Side Code:
import java.net.Socket; 
import java.io.OutputStream;
import java.io.DataOutputStream;
 
public class SCPTL
{
   public static void main(String args[]) throws Exception
   {
     Socket sock = new Socket("localhost", 5000);       
     String message1 = "Learn-Intern-Certify  from SCPTL";
 
     OutputStream ostream = sock.getOutputStream();                 
     DataOutputStream dos = new DataOutputStream(ostream);
     dos.writeBytes(message1);                                                         
     dos.close();                            
     ostream.close();   
     sock.close();
  }
}

Server Side Code:
import java.net.ServerSocket;            
import java.net.Socket;            
import java.io.*;

public class SERVER
{
   public static void main(String args[]) throws Exception
   {
     ServerSocket sersock = new ServerSocket(5000); 
     System.out.println("server is ready");  //  message to know the server is running
 
     Socket sock = sersock.accept();               
                                                                                      
     BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));

     String message2 = br.readLine();
     System.out.println(message2);
    sock.close(); sersock.close();
  }
}

Output:

Client:

Client side output

Popular posts from this blog

MongoDB - daTa ModeLLinG Concepts: SQL - Where all to UsE ?

Comparing Bootstrap With Google's Material Design Lite : Bootstrap - ResponSive Design

MongoDB overView with Installation_procEss: SQL - Where all to UsE ?