Question:
I want to send a list of numbers to the server so that when it reads them, it performs the corresponding operations and returns the result of the same to the client. Then it will ask the client for numbers again and again it will return the corresponding result, repeating the process until the client enters a *, then the connection with the server would be closed. I have to do it using UDP protocol.
The problem is that when sending the numbers, it seems that the server does not receive these numbers and it does nothing. When I run the program it asks me for the 4 numbers, I enter them and that is where it stops, the server does not return any results. To save the numbers I have used the ArrayList numbers … the problem is the process to pack that list of numbers in bytes, send it to the server and have it decode and read those numbers, there apparently the information does not reach the server . I am a newbie in this of TCP / UDP connections, I am sure I was wrong but I do not know how to solve it, I hope you can guide me a bit, because I am more lost than an octopus in a garage.
The server code is is:
import java.awt.List;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
public class Servidor {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9886);
byte[] infoRecibida = new byte[1024];
byte[] infoEnviada = new byte[1024];
byte[] paquete = new byte[1024];
String cadena;
List list;
int n1,n2,n3,n4;
int res;
String num;
String num1,num2,num3,num4;
String x;
while (true) {
System.out.println("Esperando datagrama...");
infoRecibida = new byte[1024];
DatagramPacket paqRecibido = new DatagramPacket(infoRecibida, infoRecibida.length);
serverSocket.receive(paqRecibido);
// IP y puerto desde donde se manda mensaje
InetAddress IPOrigen = paqRecibido.getAddress();
int puerto = paqRecibido.getPort();
//Estas dos lineas supuestamente serían para poder leer el arraylist enviado desde el cliente, aunque igual estoy equivocado
ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(infoRecibida));
ArrayList<Integer> numeros = (ArrayList<Integer>)inputStream.readObject();
n1 = numeros.get(0);
n2 = numeros.get(1);
n3 = numeros.get(2);
n4 = numeros.get(3);
num1= Integer.toString(n1);
num2= Integer.toString(n2);
num3= Integer.toString(n3);
num4= Integer.toString(n4);
// Si alguno de los números introducidos es *
// envío "x" al cliente para que este se cierre, posteriormente sale del bucle y se cierra también el servidor
if (num1=="*"||num2=="*"||num3=="*"||num4=="*") {
x = "x";
paquete = x.getBytes();
DatagramPacket paqueteFinal = new DatagramPacket(paquete, paquete.length, IPOrigen, puerto);
break;
}
//Hago las operaciones, el resultado lo paso a cadena y luego a bytes, para ser enviado al cliente
res=(n1+n2)*n3-n4;
num = Integer.toString(res);
infoEnviada=num.getBytes();
// ENVIO DATAGRAMA AL CLIENTE
DatagramPacket paqEnviado = new DatagramPacket(infoEnviada, infoEnviada.length, IPOrigen, puerto);
serverSocket.send(paqEnviado);
} //Fin While
serverSocket.close();
System.out.println("Socket cerrado...");
}
}
And that of the Client is
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
public class Cliente {
public static void main(String[] args) throws Exception {
String cadena;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
//para recibir y enviar datos
byte[] datosEnviados = new byte[1024];
byte[] datosRecibidos = new byte[1024];
InetAddress IPServidor = InetAddress.getByName(...); //En el paréntesis iría el número de ip del servidor adonde quiero mandarlo
int puerto = 6000;
ArrayList<Integer> numeros = new ArrayList<>();
while(true) {
//Rellenamos ArrayList numeros
for(int i=0; i<4;i++) {
System.out.println("Introduce un mensaje: ");
cadena = in.readLine();
numeros.add(Integer.parseInt(cadena));
}
//Empaquetamos ArrayList en bytes para poder enviarlo al servidor
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream outputStream = new ObjectOutputStream(out);
outputStream.writeObject(numeros);
byte[] listData = out.toByteArray();
DatagramPacket envio = new DatagramPacket(listData, listData.length, IPServidor, puerto);
clientSocket.send(envio);
outputStream.close();
//recibimos respuesta del servidor
DatagramPacket recibo = new DatagramPacket(datosRecibidos, datosRecibidos.length);
System.out.println("Esperando datagrama...");
clientSocket.receive(recibo);
String numero = new String(recibo.getData());
//Si el dato que devuelve el servidor es "x", salimos del bucle y se cierra el cliente
if (numero.equals("x")) {
break;
}
System.out.println("\t Datos: " + numero);
} //Fin While
clientSocket.close(); //Cerramos cliente
}
}
Answer:
Apparently the task he had to do was to put a single string with 4 numbers separated by a space. And the program do the operations and then return the result to me. In other words, the way of approaching the exercise was different. I have modified it, now it does not stop, but it gives me an error that I do not understand well. The codes are:
For customer:
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
public class Cliente {
public static void main(String[] args) throws Exception {
String cadena;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
byte[] listData = new byte[1024];
byte[] datosEnviados = new byte[1024];
byte[] datosRecibidos = new byte[1024];
InetAddress IPServidor = InetAddress.getByName("192.168.1.127");
int puerto = 6000;
while(true) {
System.out.println("Introduce 4 números separados por un espacio en blanco: ");
cadena = in.readLine();
listData = cadena.getBytes();
DatagramPacket envio = new DatagramPacket(listData, listData.length, IPServidor, puerto);
clientSocket.send(envio);
//recibimos respuesta del servidor
DatagramPacket recibo = new DatagramPacket(datosRecibidos, datosRecibidos.length);
System.out.println("Esperando datagrama...");
clientSocket.receive(recibo);
String numero = new String(recibo.getData());
if (numero.equals("x")) {
break;
}
System.out.println("\t Datos: " + numero);
} //Fin While
clientSocket.close(); //Cerramos cliente
}
}
For server:
import java.awt.List;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
public class Servidor {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(6000);
byte[] infoRecibida = new byte[1024];
byte[] infoEnviada = new byte[1024];
byte[] paquete = new byte[1024];
String cadena;
List list;
int n1,n2,n3,n4;
int res;
String num;
String num1,num2,num3,num4;
String x;
while (true) {
System.out.println("Esperando datagrama...");
infoRecibida = new byte[1024];
DatagramPacket paqRecibido = new DatagramPacket(infoRecibida, infoRecibida.length);
serverSocket.receive(paqRecibido);
cadena = new String(paqRecibido.getData());
// IP y puerto desde donde se manda mensaje
InetAddress IPOrigen = paqRecibido.getAddress();
int puerto = paqRecibido.getPort();
String[] numeros = cadena.split(" ");
n1 = Integer.parseInt(numeros[0]);
n2 = Integer.parseInt(numeros[1]);
n3 = Integer.parseInt(numeros[2]);
n4 = Integer.parseInt(numeros[3]);
num1= Integer.toString(n1);
num2= Integer.toString(n2);
num3= Integer.toString(n3);
num4= Integer.toString(n4);
// Si alguno de los números introducidos es *
// envío "x" al cliente para que este se cierre, posteriormente sale del bucle y se cierra también el servidor
if (num1=="*"||num2=="*"||num3=="*"||num4=="*") {
x = "x";
paquete = x.getBytes();
DatagramPacket paqueteFinal = new DatagramPacket(paquete, paquete.length, IPOrigen, puerto);
break;
}
//Hago las operaciones, el resultado lo paso a cadena y luego a bytes, para ser enviado al cliente
res=(n1+n2)*n3;
num = Integer.toString(res);
infoEnviada=num.getBytes();
// ENVIO DATAGRAMA AL CLIENTE
DatagramPacket paqEnviado = new DatagramPacket(infoEnviada, infoEnviada.length, IPOrigen, puerto);
serverSocket.send(paqEnviado);
} //Fin While
serverSocket.close();
System.out.println("Socket cerrado...");
}
}
The error that marks me is
Exception in thread "main" java.lang.NumberFormatException: For input string: "4
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Servidor.main(Servidor.java:43)