Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Networking application in regards to boolean

$
0
0
Hi everyone,

Thanks for taking your time to read my post and double thanks for giving some input!

We have two programs, I understand the datagram socket/packet, byte, send() and receive() methods.I need help understanding the Boolean true and false here as well as the try block and catch. We don't have to code anything just yet, just understand the program, I've been fine till I've hit the boolean.

Two programs. Server replies to packets sent by this program, it however drops packet to imitate an unreliable server/connection type of scenario (Math.random() was used to do this). The timeout drops to 0, making the client send again the packet/s until receipt from server is successful (sorry if i have confused you great people).

Please read on and thank you!

Such as line 10 = false - I am thinking you have to initialize this first in order to enter the while loop?
Then again with line 12, while(!received) I say this is to enter the while loop as nothing yet has been received - not sure? :(/>/>/>/>
Line 13 I'm not sure with received = true is here or used - best guess is to ensure we can first send the packet via the socket.

Not sure with the try and catch block too. I'm sure line 27 received = false; keeps the program going in the while loop until while statement becomes other than NOT false i.e. when received = true, exit while loop.



import java.io.*;
import java.net.*;

public class ReliableClient
{
  public static void main(String args[]) throws IOException
  {
    DatagramSocket ds = new DatagramSocket();
    ds.setSoTimeout(1000);
    boolean received = false;

    while (!received) 
    {
      received = true;
      String msg = new String("HELLO COMRADE");
      DatagramPacket req = new DatagramPacket(msg.getBytes(),
        msg.length(), InetAddress.getByName("127.0.0.1"), 10007);
      ds.send(req);
      System.out.println("Packet sent.");

      byte[] buf = new byte[8192];
      DatagramPacket res = new DatagramPacket(buf, buf.length);
      
      try 
      {
        ds.receive(res);
        System.out.println("Packet received.");
      } 
      catch (SocketTimeoutException e) 
      {
        received = false;
        System.out.println("Timeout. Resending...");
      }
    }
  }
}




Many thanks,

Dan

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>