I am currently writing two java classes (client and server). The client takes an input number form keyboard and sends it to the server. The server then multiplies this number by two and sends it back to the client. The numbers should also be printed to screen along the way, for example if I input the number 3 I should get
"From Client: 3" "From Server: 6"
They should continuously do this unless a negative number is received by the client, say for example the number -3 is sent to the server and it returns -6.
The code I have for the two classes so far is:
import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.util.Scanner; class Client { public static void main(String args[]) throws Exception { DatagramSocket clientSocket = new DatagramSocket(); System.out.println("Insert number: "); Scanner s= new Scanner(System.in); int num = s.nextInt(); byte[] sendData = ByteBuffer.allocate(4).putInt(num).array(); InetAddress IPAddress = InetAddress.getByName("localhost"); int port = 1999; DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length , IPAddress ,1999); clientSocket.send(sendPacket); BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in)); byte[] receiveData = new byte[4]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); int numberReceived = ByteBuffer.wrap(receivePacket.getData()).getInt(); System.out.println("FROM SERVER:" + numberReceived); clientSocket.close(); } }
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.nio.ByteBuffer; class Server { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(1999); while(true) { byte[] receiveData = new byte[4]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); int num = ByteBuffer.wrap(receivePacket.getData()).getInt(); System.out.println("FROM Client:" + num); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); int numtosend = num * 2; byte[] sendData = ByteBuffer.allocate(4).putInt(numtosend).array(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,port); serverSocket.send(sendPacket); } } }
Currently, when I run the program all I get is an output of the number first entered.
Can anyone tell me where I am going wrong?
I am aware it requires a loop but I don't know where and what the condition should be.
Many thanks in advance