Java – Stop and wait UDP server

javasocketsudp

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 ? :

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

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) {
      System.err.println(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);
      clientSocket.send(sendPacket);
      clientSocket.setSoTimeout(1);
      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
      if(clientSocket.receive(receivePacket)==null)
      {
       clientSocet.send(sendPacket); 
      }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 ) {
        clientSocket.close();
      }
      }}}}

Best Answer

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 {
    clientSocket.receive(receivePacket);
    sequenceNo++;
    ... // rest of the success path
} catch (SocketTimeoutException ex) {
    clientSocket.send(sendPacket);
}