How to create an concurrent server using java


What is concurrent server ?

Concurrent server is server which able to handle multiple request at the same time.  Concurrent server create child server for each request. Concurrent server accept the request from client , this request pass to child server and concurrent server able to accept new request, where child server process that request and response to client.

Concurrent server in Java

In java we use an multithreading to create an concurrent server.

ChildServer
  • First create an ChildServer class which is extends by Thread class for perform individual task.

     class ChildServer extends Thread{  
     }  
    

  • Then ChildServer create connection with Client using Socket, This Socket is that which is used by ConcueentServer for accepting client.
  • Using this Socket ChildServer is communicate with Client

     ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());  
     ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());  
    

  • This communication is done in run() method which is override from Thread class.

ConcurrentServer

  • Create an ServerSocket in Concurrent Server which accept the request from client.

     ServerSocket sSocket = new ServerSocket(1234);  
    
  • Accept the Client request using Socket

     Socket socket = sSocket.accept();  
    

  • Now create an object of ChildServer object with accepted socket.
  •  ChildServer cServer = new ChildServer(socket);  
    
  • and Run ChildServer Thread to activate child server tasking.

     cServer.start();  
    


Full Working Code

 import java.io.IOException;  
 import java.io.ObjectInputStream;  
 import java.io.ObjectOutputStream;  
 import java.net.ServerSocket;  
 import java.net.Socket;  
   
 public class ConcurrentServer {  
   
   final private static int port = 1234;  
   
   public static void main(String args[]) {  
     try {  
       ServerSocket sSocket = new ServerSocket(port);  
       while (true) {   // use infinte loop for accepting request        
         Socket socket = sSocket.accept();  
         ChildServer cServer = new ChildServer(socket);  
         cServer.start();  
       }  
     } catch (IOException ex) {  
       System.out.println(ex);  
     }  
   }  
 }  
   
 class ChildServer extends Thread {  
   
   Socket socket;  
   ObjectInputStream ois;  
   ObjectOutputStream oos;  
     
   public ChildServer(Socket socket) {  
     try {  
       this.socket = socket;  
       ois = new ObjectInputStream(socket.getInputStream());  
       oos = new ObjectOutputStream(socket.getOutputStream());  
     } catch (IOException ex) {  
       System.out.println(ex);  
     }  
   }  
   
   @Override  
   public void run() {  
     // processing request and responce to client  
   }  
 }  
   

No comments:

Post a Comment