I have to write a client and server class for a UDP protocol sending integer numbers by UDP packets. So far i have this;
Client Code:
import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String args[]) throws Exception {
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("hostname");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
Server Code:
import java.io.*;
import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
}
}
}
But i now need to change this so that:
The client;
1. Reads an integer from keyboard input and stores its value in a UDP packet. // byte[] send = ByteBuffer.allocate(4).putInt(num).array(); ???
2. Sends the UDP packet to the server, on port number 1999;
3. Listens for UDP packets from the server (until it receives a packet with a non-positive number; see
step (b) below). While listening:
(a) Once it receives a UDP packet from the server, it subtracts 2 from the integer value num contained
in it. // int num = ByteBuffer.wrap(receive).getInt(); ???
(b) Checks the integer value num: if the value is greater than 0 (num>0) then the client stores it in a
new UDP packet and sends the packet to the server; otherwise (num<=0) the client terminates.
The Server;
1. Listens on port 1999;
2. For each UDP packet it receives from a client:
(a) extracts the integer value n contained in it;
(b) decreases the value of n by 2;
(c) sends back to the client a UDP packet containing the new value of n.