I've been given this question and I've been trying since days but I'm not able to get the correct output. Any help would be appreciated.
Develop a simple chat application between two users using Send-Wait-Receive
Protocol:
Once a user sends a message, he waits until a message is received from the other user. The users are "User1" and "User2".
At initial stage of application, User1 is in sending mode and User2 is in receiving mode. These two users are sending and receiving the messages alternatively. -Create a Chat class with two methods: sendMessage and recvMessage -Create two threads to represent two users,User1 and User2. -Use Interthread communication to exchange messages. -No need to maintain any chat history.
OUTPUT:
User1(User2):HI
User2(User1):HI
User2(User1):Hello
User1(User2):Hello
class Chat{
Scanner sc=new Scanner(System.in);
String message;
ArrayList<String> user1 = new ArrayList<String>();
ArrayList<String> user2 = new ArrayList<String>();
boolean sendMode = true;
String name = "";
String otherName = "";
synchronized void recvMessage(){
name = Thread.currentThread().getName();
while(sendMode) {
try{
wait();
}catch(InterruptedException e){
System.out.println("InterruptedException caught");
}
}
System.out.println(name);
if (name.contentEquals("User1")) {
otherName="User2";
}
else {
otherName="User1";
}
System.out.println(name+"("+otherName+"):" + message);
sendMode=true;
System.out.println("rcv");
notify();
}
synchronized void sendMessage(){
name = Thread.currentThread().getName();
while(!sendMode) {
try{
wait();
}catch(InterruptedException e){
System.out.println("InterruptedException caught");
}
}
System.out.println(name);
if (name.contentEquals("User1")) {
otherName="User2";
}
else {
otherName="User1";
}
System.out.print(name+"("+otherName+"):");
message=sc.next();
if(name.contains("User1")) {
user1.add(message);
}
else {
user2.add(message);
}
System.out.println("send");
sendMode=false;
notify();
}
}
class Person1 implements Runnable{
Chat ex;
public Person1(Chat ex) {
this.ex = ex;
Thread u2=new Thread(this, "User1");
u2.start();
}
public void run() {
while(true) {
ex.sendMessage();
}
}
}
class Person2 implements Runnable{
Chat ex;
public Person2(Chat ex) {
this.ex=ex;
Thread u1=new Thread(this, "User2");
u1.start();
}
public void run() {
while(true) {
ex.recvMessage();
}
}
}
class Main{
public static void main(String args[])
{
Chat ex =new Chat();
new Person1(ex);
new Person2(ex);
}
}
the output I'm getting is: User1(User2):hi
User2(User1):hi
User2(User1):hello
User1(User2):hello
User2(User1):what's up
User1(User2):what's
User2(User1):User1(User2):up
User2(User1):
Basically the threads are not in doing their job in order. The first 4 lines of output are right. But after that, it's always user2 sending the message and user1 receiving it.
Please help me out.