Java – Stop and wait UDP server


I am trying to program a Java stop-and-wait UDP server and I have gotten this far with the server but I am not sure where to go next. I want the client to send a message to the server, set a timeout, wait for a response, if it doesn't get one, then resend the packet, if it does then increment the sequence no. until it get to ten and keep send and receiving messages with the server.

I have gotten this far, how do I fix this ? :


public class Client {
  public static void main(String args[]) throws Exception {

    byte[] sendData = new byte[1024];
    byte[] receiveData = new byte[1024];
    InetAddress IPAddress = null;

    try {
      IPAddress = InetAddress.getByName("localhost");
    } catch (UnknownHostException exception) {

    //Create a datagram socket object
    DatagramSocket clientSocket = new DatagramSocket();
    while(true) {
      String sequenceNo = "0";
      sendData = sequenceNo.getBytes();
      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 6789);
      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
      }else { //message sent and acknowledgement received
             sequenceNo++; //increment sequence no.
        //Create a new datagram packet to get the response
      String modifiedSentence = sequenceNo;
      //Print the data on the screen
      System.out.println("From :  " + modifiedSentence);
      //Close the socket
      if(sequenceNo >= 10 ) {

Best Solution

The first problem I can see (apart from the mistyped variable names which will stop your code compiling) is your socket timeout: if the socket timeout expires, the receive function will throw a SocketTimeoutException which your code does not handle. receive does not return a value, so the result can't be compared with null. Instead, you need to do something like this:

try {
    ... // rest of the success path
} catch (SocketTimeoutException ex) {