Java Program for protocol 3 with two way communication between sender and receiver

/*Here, sender will send message to receiver and wait for acknowledgment for some time(here 3 sec). If receiver failed to response acknowledgement, sender resend the same message(here, 3 times). */

//sender to send message for protocol 3

import java.io.*;
import java.net.*;
public class protocol3_Sender
{
public static void main(String args[])
{
try
{
Socket s=new Socket("localhost",6666);
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
DataInputStream dis=new DataInputStream(s.getInputStream());

BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String str="",ack="",ch="";
do
{
System.out.println("Enter your message: ");
str=br.readLine();

System.out.println("String: "+str);
dos.writeUTF(str);
ack=dis.readUTF();
for(int i=0;i<3;i++)
{
Thread.sleep(3000);
if(ack.equals(""))
{
System.out.println("Done resend ");
dos.writeUTF(str);
}
else
{
System.out.println("Server says: " +ack);
break;
}
}
System.out.println("Press 1 to continue.. ");
ch=br.readLine();
}while(ch.equals("1"));
dos.flush();
dos.close();
s.close();
}
catch(InterruptedException e)
{

System.out.println(e.getMessage());
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
//receiver to receive message for protocol 3
import java.io.*;
import java.net.*;
public class protocol3_Rec
{
public static void main(String args[])
{
try
{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();

DataInputStream dis=new DataInputStream(s.getInputStream());
DataOutputStream dos=new DataOutputStream(s.getOutputStream());

//BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String ack="We have got your message";

String msg="";
do
{
msg=dis.readUTF();
System.out.println("Given string is: "+msg);

Thread.sleep(1000);
dos.writeUTF(ack);
ack="";
}while(!msg.equals(""));

dos.flush();
dis.close();
s.close();
ss.close();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}

}
}

Comments

Popular posts from this blog

Java Program to implement binary checksum

Java Program for block parity

Welcome Guide to Swift 5 Escaping String