Showing posts with label Multithreading. Show all posts
Showing posts with label Multithreading. Show all posts

Monday, 24 September 2018

Write a Mulitithreaded TCP Server which will send system data and time to clinet.

Multithreaded TCP server:

import java.io.*;
import java.net.*;
import java.util.*;
public class MultiServe implements Runnable
{
 private ServerSocket ss;
 public static void main(String args[]) throws Exception
 {
  MultiServe m = new MultiServe();
  m.go();
 }
 public void go() throws Exception
 {
  ss = new ServerSocket(DayClient1.DAYTIME_PORT, 5);
  Thread t1 = new Thread(this, "1");
  Thread t2 = new Thread(this, "2");
  Thread t3 = new Thread(this, "3");
  t1.start(); t2.start(); t3.start();
 }
 public void run()
 {
  Socket s = null;
  BufferedWriter out = null;
  String myname = Thread.currentThread().getName();
  for (;;)
  {
   try
   {
    System.out.println("thread " + myname + " about to accept..");
    s = ss.accept();
    System.out.println("thread " + myname + " accepted a connection");
    out = new BufferedWriter(
    new OutputStreamWriter(s.getOutputStream()));
    out.write(myname + " " + new Date());
    Thread.sleep(10000);
    out.write("\n");
    out.close();
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
  }
 }
}

Client:

//A TCP Client for the Daytime service
import java.net.*;
import java.io.*;
public class DayClient1 {
public static final int DAYTIME_PORT = 2012;
String host;
Socket s;
public static void main(String args[]) throws
IOException {
DayClient1 that = new DayClient1("192.681.158.1");
that.go();
}
public DayClient1(String host) {
this.host = host;
}
public void go() throws IOException {
s = new Socket(host, DAYTIME_PORT);
BufferedReader i = new BufferedReader(
new InputStreamReader(s.getInputStream()));
System.out.println(i.readLine());
i.close();
s.close();
}
}

Output:


‘OR’

Server:

import java.io.*;
import java.net.*;
public final class TcpServerStarter 
{
 public static void main(String[] args) throws IOException 
 {
  ServerSocket serverSocket = null;
  boolean listening = true;
  try 
  {
   serverSocket = new ServerSocket(2012);
  } 
  catch (IOException e) 
  {
   System.err.println("Could not listen on port: 2012.");
   System.exit(-1);
  }
  while (listening)
  new ConnectionHandler( serverSocket.accept()).start();
  serverSocket.close();
 }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
public final class ConnectionHandler extends Thread {
    private Socket socket;
    public ConnectionHandler(Socket socket){
          setName("ConnectionHandler");
          this.socket = socket;
    }
    public void run(){
          BufferedReader in = null;
          PrintWriter out = null;
          String request;
          try{
                // Get the input and output streams
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                while( (request = in.readLine()) != null){

                      // Deliver the current date and time if the client sends GET_TIME
                      if(request.equals("GET_TIME"))
                            out.println(new Date().toString());

                      // Deliver the JRE version if the client sends GET_JAVA_VERSION
                      else if(request.equals("GET_JAVA_VERSION"))
                            out.println(System.getProperty("java.version"));

                      // Exit the loop if the client sends CLOSE
                      else if(request.equals("CLOSE"))
                            break;
                }
          }
          catch(IOException e){
                e.printStackTrace();
          }
          finally{
                try{
                      if(socket != null)
                  socket.close(); // Close the socket (closing the socket also closes the input and output streams)
                }
                catch(IOException e){
                      e.printStackTrace();
                }
          }
    }
}

Client:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public final class TcpClient {
    private void process() {
          Socket socket = null;
          BufferedReader in = null;
          PrintWriter out = null;
          try{
                /* Establish a TCP connection with the server running locally on the port number 2012.
                 * You can write "localhost" instead of "192.681.158.1".
                                  */
                socket = new Socket("192.681.158.1", 2012);

                // Get the input and output streams
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                // Send a GET_TIME request and print the response to the standard output
                out.println("GET_TIME");
                System.out.println(in.readLine());

                // Send a GET_JAVA_VERSION request and print the response to the standard output
                out.println("GET_JAVA_VERSION");
                System.out.println(in.readLine());

                // Send a CLOSE request to the server to end communication
                out.println("CLOSE");
          }
          catch(IOException e){
                e.printStackTrace();
          }
          finally{
                try{
                      if(socket != null)
                            socket.close(); // Close the socket (closing the socket also closes the input and output streams)
                }
                catch(IOException e){
                      e.printStackTrace();
                }
          }
    }
    public static void main(String[] args){
          new TcpClient().process();
    }
}

Output:


Multithreading Program in Java

Write down a complete multithreaded connection oriented socket based server, that'll wait for the connections from clients, after the establishment of connection with client, it will receive a string word from the client and send it back the meaning of that word from the array stored on server to client. 


Multithreaded Server Starter: 

import java.io.*;
import java.net.*;
public final class TcpServerStarter 
{
 public static void main(String[] args) throws IOException 
 {
  ServerSocket serverSocket = null;
  boolean listening = true;
  try 
  {
   serverSocket = new ServerSocket(7777);
  } 
  catch (IOException e) 
  {
   System.err.println("Could not listen on port: 7777.");
   System.exit(-1);
  }
  while (listening){
  new P10_5( serverSocket.accept()).start();
  System.out.println("Accepted connection from client");}
  serverSocket.close();
 }
}

Multithreaded Server:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public final class P10_5 extends Thread {
    private final Socket socket;
    public P10_5(Socket socket) {
        setName("P10_5");
        this.socket = socket;
    }
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        int n = 3;
        String request;
        try {
            // Get the input and output streams
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            class dic {
                String word, mean;
                dic(String w, String m) {
                    word = w;
                    mean = m;
                }
            }
            dic d[] = new dic[4];
            d[0] = new dic("coincidence", "itifaq");
            d[1] = new dic("thanks", "shukriya");
            d[2] = new dic("problem", "masla");
            d[3] = new dic("night", "raat");
            while ((request = in.readLine()) != null) {
                for (int i = 0; i < n; i++) {
                    if (request.equals(d[i].word)) {
                        out.println(d[i].mean);
                        break;
                    }
                    if (i == n - 1) {
                        out.println("No knowledge for " + request);
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close(); // Close the socket (closing the socket also closes the input and output streams)
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Client:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public final class P10_5Client {
    private void process() {
        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            /* Establish a TCP refrenced to  the server running locally on the port number 7777.
             * You can write "localhost" instead of "127.0.0.1".
             * If the server is running on a foriegn computer, replace "127.0.0.1" with the server's IP address or hostname
             */
            socket = new Socket("127.0.0.1", 7777);
            // Get the input and output streams
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            Scanner user = new Scanner(System.in); // Scanning for user input
            String input;
            while (true) {
                System.out.print("Enter String: ");
                input = user.next(); // Hold the input from the user
                if (input.equals("end")) {
                    System.out.println("You ended...");
                    break;
                } else {
                    out.println(input); // Send it to the server
                    System.out.println("Name: " + input + " Meaning: " + in.readLine());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close(); // Close the socket (closing the socket also closes the input and output streams)
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        new P10_5Client().process();
    }
}

Output:





Methods in JAVA Language

 In general, a way may be thanks to perform some task. Similarly, the tactic in Java may be a collection of instructions that performs a sel...