简体   繁体   English

通过datagramsocket(Java)获取IOException接收datagrampakcet

[英]Getting IOException receiving datagrampakcet through datagramsocket (Java)

I am trying to use a dagramsocket to send packages from a client to a server, but after spending some hours looking for information in StackOverflow and the offical documentation, I am still getting a IOException. 我正在尝试使用dagramsocket将包从客户端发送到服务器,但是花了几个小时在StackOverflow和官方文档中查找信息之后,我仍然收到IOException。 I have a server, with recieve a sentence from a client, change the sentence and print the new sentence. 我有一台服务器,可以从客户端接收一个句子,更改句子并打印新句子。 Any idea why it is not working? 知道为什么它不起作用吗? Here is the code: 这是代码:

Client: 客户:

public class YodafyClienteTCP {

    public static void main(String[] args) {

        byte []buferEnvio;
        byte []buferRecepcion=new byte[256];
        int bytesLeidos=0;

        // Nombre del host donde se ejecuta el servidor:
        String host="localhost";
        // Puerto en el que espera el servidor:
        int port=8989;
        DatagramPacket paquete;
        InetAddress direccion;

        // Socket para la conexión TCP
        DatagramSocket socketServicio;

        try {
            // Creamos un socket que se conecte a "host" y "port":

            socketServicio=new DatagramSocket();
            direccion = InetAddress.getByName(host);

            buferEnvio="Al monte del volcán debes ir sin demora".getBytes();

            paquete = new DatagramPacket(buferEnvio, buferEnvio.length, direccion, port);

            // Enviamos el array por el socket;
            socketServicio.send(paquete);
            System.out.println("Paquete enviado por el cliente.");

        socketServicio.close();

            // Excepciones:
        } catch (UnknownHostException e) {
            System.err.println("Error: Nombre de host no encontrado.");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Error de entrada/salida al abrir el socket.");
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

Class which change sentence, invoked by server 由服务器调用的更改句子的类

public class ProcesadorYodafy {
    // Referencia a un socket para enviar/recibir las peticiones/respuestas
    private DatagramSocket socketServicio;


    // Para que la respuesta sea siempre diferente, usamos un generador de números aleatorios.
    private Random random;

    // Constructor que tiene como parámetro una referencia al socket abierto en por otra clase
    public ProcesadorYodafy(DatagramSocket socketServicio) {
        this.socketServicio=socketServicio;
        random=new Random();
    }


    // Aquí es donde se realiza el procesamiento realmente:
    void procesa(){

        // Como máximo leeremos un bloque de 1024 bytes. Esto se puede modificar.
        byte [] datosRecibidos=new byte[1024];
        int bytesRecibidos=0;
        DatagramPacket paquete;

        // Array de bytes para enviar la respuesta. Podemos reservar memoria cuando vayamos a enviarla:
        byte [] datosEnviar;


        try {
            // Lee la frase a Yodaficar:
            paquete = new DatagramPacket(datosRecibidos, datosRecibidos.length);
            socketServicio.receive(paquete);

            datosRecibidos = paquete.getData();
            bytesRecibidos = datosRecibidos.length;

            //yodaDo is just a method that changes some characters in the sentence
            String peticion=new String(datosRecibidos,0,bytesRecibidos);
            String respuesta=yodaDo(peticion);
            System.out.println("Here is your new sentence : " + respuesta);         

            socketServicio.close();

        } catch (IOException e) {
            System.err.println("Error al obtener los flujos de entrada/salida.");
        }

    }

Server: 服务器:

public class YodafyServidorIterativo {

    public static void main(String[] args) {

        // Puerto de escucha
        int port=8989;
        // array de bytes auxiliar para recibir o enviar datos.
        byte []buffer=new byte[256];
        // Número de bytes leídos
        int bytesLeidos=0;
        //Socket
        DatagramSocket socketServicio;

        try {
            // Abrimos el socket en modo pasivo, escuchando el en puerto indicado por "port"
            socketServicio = new DatagramSocket(port);
                        // Mientras ... siempre!
            do {
                //////////////////////////////////////////////////

                // Creamos un objeto de la clase ProcesadorYodafy, pasándole como
                // argumento el nuevo socket, para que realice el procesamiento
                // Este esquema permite que se puedan usar hebras más fácilmente.
                ProcesadorYodafy procesador=new ProcesadorYodafy(socketServicio);
                procesador.procesa();

            } while (true);

        } catch (IOException e) {
            System.err.println("Error al escuchar en el puerto "+port);
        }

    }

}

First of all, this is a UDP connection, like mention here . 首先,这是一个UDP连接,如此处所述 Looking for the right connection you gonna find more fast the need documentation. 寻找正确的连接,您会更快地找到需求文档。

Second, probably your problem, whenever it is, is cause by: 其次,无论您遇到什么问题,可能是由以下原因引起的:

  1. One of your services isn't start or 您的一项服务无法启动或
  2. You don't set the port of your client application and, thinking you're using this locally, can cause conflicts of resources. 您没有设置客户端应用程序的端口,并且以为您在本地使用它可能会导致资源冲突。

Try to set the port of your client and make sure your server is started before start you client. 尝试设置客户端的端口,并在启动客户端之前确保服务器已启动。

Solved. 解决了。 I was closing the datagramsocket in the class ProcesadorYodafy and opening the socket only once in the server, so in the following iteration of the loop, the datagramsocket was closed despite the fact I was sending there the package. 我正在关闭ProcesadorYodafy类中的datagramsocket,并且只在服务器中打开了一次套接字,因此在循环的以下迭代中,尽管我将包发送到了那里,但datagramsocket还是关闭了。 Thanks everybody 谢谢大家

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM