Question

I need to send a message saying "Hi" from client to a server, the server will reply back to the client adding to the received message "Received", once the client receives this new message it will send this to another server and that server will add another message to the received message saying "Replied". So in the end the client will receive the message "Hi Received Replied". Client code:

public class UDPClient{    

public static void main(String args[]) {  
        // args[0] = message to be sent to the server; 
    // args[1] = IP address of the server

    DatagramSocket aSocket=null;
    try {
        aSocket=new DatagramSocket();
        byte [] m = args[0].getBytes();
        InetAddress aHost = InetAddress.getByName(args[1]);
        int serverPort = 6789;

DatagramPacket request = new DatagramPacket(m,args[0].length(), aHost, serverPort);
        aSocket.send(request);                                  

        byte[] buffer = new byte[1000];
        DatagramPacket reply = new DatagramPacket(buffer,buffer.length);
        aSocket.receive(reply);     
System.out.println("Reply: " + new String(reply.getData(), 0, reply.getLength()));

    }catch (SocketException e){System.out.println("Socket: " + e.getMessage());
    }catch (IOException e){System.out.println("IO: " + e.getMessage());
    }finally {
        if(aSocket != null) aSocket.close();
    }
}
}

Server Code:

public class UDPServer{    
public static void main(String args[]) {        
   DatagramSocket aSocket = null;

try{            
    aSocket = new DatagramSocket(6789);  
    byte[] buffer = new byte[1000];             
    while(true){                
DatagramPacket request = new DatagramPacket(buffer,buffer.length);
aSocket.receive(request); 

System.out.println("Server is ready and waiting for requests ... "); 
DatagramPacket reply = new DatagramPacket(request.getData(), request.getLength(),request.getAddress(), request.getPort());

     }      
}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
}catch (IOException e) {System.out.println("IO: " + e.getMessage());
}finally {
    if(aSocket != null) aSocket.close();
}
  }
}

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top