3) Write a Java Program that simulates Client-Server Interaction using threads.
Methodology: Two threads should be created; one thread should act as Server, and the other
one should act as Client. The Server thread should accept a String request from Client thread,
parse that request and print the length of the string. It should also send back the
acknowledgement message “Message Received” to Client Thread. The Client thread should
terminate only when it receives acknowledgement from Server thread.
import java.util.Scanner;
class Qa {
int n;
String msg="a";
boolean valueSet = false;
synchronized String get() {
while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
valueSet = false;
notify();
return msg;
}
synchronized void put(String msg) {
while (valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.msg=msg;
valueSet =true;
notify();
}
}
class Server implements Runnable {
Qa q;
String msg="a";
Server(Qa q) {
this.q = q;
new Thread(this, "Server").start();
}
public void run() {
msg=q.get();
System.out.println("Message:"+msg);
System.out.println("Message Length "+msg.length());
q.put("Message Received");
}
}
class Client implements Runnable {
Qa q;
Scanner input=new Scanner(System.in);
String msg;
Client(Qa q) {
this.q = q;
new Thread(this, "Client").start();
}
public void run() {
System.out.println("Enter the String");
msg=input.nextLine();
q.put(msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(!(msg=q.get()).equals("Message Received"));
System.out.println("Message Received");
}
}
class clientserverthread {
public static void main(String args[]) {
Qa q = new Qa();
new Client(q);
new Server(q);
}
}
OUTPUT-:
Enter the String
java is awesome
Message:java is awesome
Message Length 15
Message Received
0 comments:
Post a Comment