如何使用UDP从客户端向服务器发送ArrayList?

时间:2019-05-26 23:47:15

标签: java udp

我想将数字列表发送到服务器,以便在读取它们时执行相应的操作,并将结果返回给客户端。

然后它将再次向客户询问编号,并将重复该操作,并再次返回相应的结果,重复此过程,直到客户端输入“ *”,然后将与服务器建立封闭连接。我必须使用UDP协议来强制执行此操作。

问题在于,显然将数字发送到服务器无法达到这些数字,因此不执行任何操作。当我运行程序时,他要求我输入4个数字,然后将它们写出来,这就是停止的地方,服务器不会返回任何结果。为了保存我使用ArrayList数字的数字...问题是将数字列表打包为字节,将其发送到服务器,然后解码并读取这些数字的过程,显然信息没有到达 到服务器。我是这个TCP / UDP连接的新手,我确定我会犯一个错误,但是我不知道如何解决,希望您能对我有所帮助,因为我不知道这是什么失败。

服务器代码:

package muestraUDP;

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("Waiting datagrama...");            
            infoRecibida = new byte[1024];
            DatagramPacket paqRecibido = new DatagramPacket(infoRecibida, infoRecibida.length);
            serverSocket.receive(paqRecibido);            


         // IP and port from which message is sent
            InetAddress IPOrigen = paqRecibido.getAddress();
            int puerto = paqRecibido.getPort();


            //These two lines supposedly would be to be able to read the arraylist sent from the client, although I am still wrong

            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);


            // If any of the numbers entered is * 
            // sending "x" to the client so that it closes, then exits the loop and the server is also closed

            if (num1=="*"||num2=="*"||num3=="*"||num4=="*") {
                x = "x";
                paquete = x.getBytes();
                DatagramPacket paqueteFinal = new DatagramPacket(paquete, paquete.length, IPOrigen, puerto);
                break;
            }


            //I do the operations, the result is passed to the string and then to bytes, to be sent to the client

            res=(n1+n2)*n3-n4;
            num = Integer.toString(res);                      
            infoEnviada=num.getBytes();



            // Sending Datagrama to client

            DatagramPacket paqEnviado = new DatagramPacket(infoEnviada, infoEnviada.length, IPOrigen, puerto);
            serverSocket.send(paqEnviado);

        } //End of While


        serverSocket.close();
        System.out.println("Socket cerrado...");

    }

}

和客户代码:

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();


        //for receiving and sending data

        byte[] datosEnviados = new byte[1024];
        byte[] datosRecibidos = new byte[1024];


        InetAddress IPServidor = InetAddress.getByName(...); //In the parentheses would go the ip number of the server where I want to send it
        int puerto = 6000;

        ArrayList<Integer> numeros = new ArrayList<>();

        while(true) {

            //Fill in ArrayList numbers

            for(int i=0; i<4;i++) {
                System.out.println("Introduce un mensaje: ");
                cadena = in.readLine();
                numeros.add(Integer.parseInt(cadena));          
            }


            //We pack ArrayList in bytes to be able to send it to the server

            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();


            //we received response from the server

            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);      

        } //End of While

        clientSocket.close(); //Close client
    }

}

0 个答案:

没有答案