1

Mi pregunta es acerca de Java.

No logro recibir los paquetes en bytes.

Estoy tratando de conectarme a un servidor de chat y recibir paquetes en bytes.

Les muestro el código:

InetAddress addr = InetAddress.getByName(ip);
                        SocketAddress sockaddr = new InetSocketAddress(addr.getHostAddress(), port);

                        sock.connect(sockaddr);
                        out = new DataOutputStream(sock.getOutputStream());
                        out.write(TCPOutbound.Login()); //hasta ahí todo sale bien
                        s.chat.append("\n" + getString(R.string.conectado));
                        conected = true;
                        while(conected == true){
                            dIn = new DataInputStream(sock.getInputStream());

                            int length = dIn.readInt();    // read length of incoming message
                            if(length>0) {
                                byte[] message = new byte[length];
                                dIn.readFully(message, 0, message.length); // no logro recibir el paquete
                                for(int f=0;f<message.length;f++){
                                    s.chat.append(convertByteToString(message[f]) + " - ");
                                }
                                s.chat.append("\n");
                            }
                        }

Me larga este error:

FATAL EXCEPTION: Thread-2
07-25 17:20:26.452 8821 8867 E     AndroidRuntime                               Process: com.mycompany.myapp, PID: 8821
07-25 17:20:26.452 8821 8867 E     AndroidRuntime                               java.lang.OutOfMemoryError: Failed to allocate a 905971256 byte allocation with 12582912 free bytes and 189MB until OOM, max allowed footprint 14792376, growth limit 201326592
07-25 17:20:26.452 8821 8867 E     AndroidRuntime                               at com.mycompany.myapp.MainActivity$100000001.run(MainActivity.java:156)
07-25 17:20:26.452 8821 8867 E     AndroidRuntime                               at java.lang.Thread.run(Thread.java:764)

¿Cómo puedo solucionar ese error?

Gracias y saludos

3
  • 1
    El método dIn.readInt(); lee 4 bytes del stream y retorna un entero. En los primeros 4 bytes está la longitud del mensaje entrante? Porque parece que está leyendo un 905971256 lo que hace que se intenten alojar casi 800 MB de espacio en memoria.
    – Lobos
    el 25 jul. 2020 a las 15:45
  • Ah, tienes razón, pero entonces cuál sería la manera correcta de recibir paquetes bytes mediante Sockets? Es decir, recibirlos sin saber la longitud... el 26 jul. 2020 a las 21:48
  • No deberias intentar almacenar el contenido completo del chat si tiene tal tamaño. Estas seguro que int length = dIn.readInt(); entrega el tamaño del mensaje, esta en el protocolo? (es decir, el chat envia un DataOutputStream?)
    – F.Igor
    el 30 jul. 2020 a las 16:58

1 respuesta 1

1

El formato del mensaje que envía el servidor es el siguiente:

2 bytes -> data length
1 byte -> proto id
x bytes -> data

En el último bloque de bytes (data) estará la secuencia: x bytes username, 1 byte null, x bytes message

EL siguiente código simula un servidor que envía mensajes con ese formato y un cliente que los lee, la parte de interés en tu problema es el cliente, el punto 2:

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Random;

public class Test {

    private static final String[] randoName = new String[]{
            "Anna", "Frank", "Peter", "Charlie", "Alice"
    };

    private static final String[] randonWord = new String[]{
            "house", "dog", "run", "eat", "pork", "hello", "bye",
            "sad", "what", "sleep"
    };

    private final static Random r = new Random(System.currentTimeMillis());

    public static void main(String... args) throws IOException {


        // 1. start chat server  simulation
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    // code that init the server and waits a client to connect
                    ServerSocket server = new ServerSocket(54444);
                    System.out.println("waiting for client to connect");
                    Socket client = server.accept();
                    System.out.println("client connected");


                    // code that send bytes to the client
                    for (; ; ) {
                        // to make a pause
                        Thread.sleep(1000);

                        // create string to be sent
                        String userName = String.format("%s",
                                randoName[r.nextInt(4)]
                        );

                        String message = String.format("%s %s %s %s",
                                randonWord[r.nextInt(9)],
                                randonWord[r.nextInt(9)],
                                randonWord[r.nextInt(9)],
                                randonWord[r.nextInt(9)]
                        );


                        /*
                         * Create byte[] message to be sent
                         * 2 bytes for message length
                         * 1 byte for procotol
                         * x bytes for messsage
                         * */

                        int userNameLen = userName.getBytes().length;
                        int messageLen = message.getBytes().length;

                        // get message length stored in short type 2 bytes
                        short messageLength = (short) (userNameLen + messageLen + 1);
                        byte[] messageLengthInBytes = ByteBuffer.allocate(2).putShort(messageLength).array();


                        // 1 byte for protocol
                        byte[] procotol = new byte[]{10};


                        // message in format x bytes for username 1 byte null and x bytes for message
                        byte[] messageByte = new byte[messageLength];

                        System.arraycopy(userName.getBytes(), 0, messageByte, 0, userNameLen);
                        System.arraycopy(new byte[]{0}, 0, messageByte, userNameLen, 1);
                        System.arraycopy(message.getBytes(), 0, messageByte, userNameLen + 1, messageLen);

                        byte[] formattedMessage = new byte[
                                messageLengthInBytes.length +
                                        procotol.length +
                                        messageByte.length
                                ];


                        // concat arrays

                        System.arraycopy(messageLengthInBytes, 0, formattedMessage, 0, 2);
                        System.arraycopy(procotol, 0, formattedMessage, 2, 1);
                        System.arraycopy(messageByte, 0, formattedMessage, 3, messageLength);


                        // write bytes to client using output stream
                        client.getOutputStream().write(formattedMessage);
                        client.getOutputStream().flush();
                    }

                } catch (Exception ignored) {
                    //System.out.println(ignored.getMessage());
                }
            }
        }).start();

        // end chat server simulation


        // 2. client simulation

        // create socket
        Socket socket = new Socket("127.0.0.1", 54444);

        InputStream in = socket.getInputStream();


        while (socket.isConnected()) {

            //  get message length, first 2 bytes
            byte[] lengthBytes = new byte[2];
            in.read(lengthBytes);
            // convert to int
            int messageLength = lengthBytes[0] << 8 | lengthBytes[1];


            // get the protocol byte
            int procotol = in.read();

            // get message, length bytes
            byte[] messageBytes = new byte[messageLength];
            in.read(messageBytes);


            // separate message, first x bytes are username
            int length = 0;

            // get username length
            for (byte messageByte : messageBytes) {
                if (messageByte == 0) break;
                length++;
            }

            // extract username
            byte[] username = new byte[length];
            System.arraycopy(messageBytes, 0, username, 0, length);

            int pos = length + 1;

            // message length
            length = messageBytes.length - pos;


            // extract message
            byte[] message = new byte[length];
            System.arraycopy(messageBytes, pos, message, 0, length);


            System.out.printf("message length: %d\nprocotol : %d\nusername: %s\nmessage: %s\n",
                    messageLength, procotol, new String(username), new String(message));


        }


    }

}
8
  • Tu código es más corto, me gustó. Tenía la esperanza de que iba a funcionar, pero no lo hizo :( Lo que necesito es recibir bytes. Y con s.nextByte(); tampoco funciona... Quizás entiendas mejor lo que quiero lograr si te muestro el código de C# que tiene la manera de recibir los paquetes bytes que quiero traducir a Java. El primer link: github.com/AresChat/cb0t/blob/master/cb0t/RoomPanel/…. El segundo link: github.com/AresChat/cb0t/blob/master/cb0t/RoomPanel/…. Para ser más específicos, se trata del paquete MSG_CHAT_SERVER_PUBLIC el 26 jul. 2020 a las 21:59
  • No sé como está implementado el servidor de chat. Agregué un código que simula un servidor que envía mensajes a sus clientes, espero te ayude. En el punto 2 está el cliente que lee esos mensajes desde el servidor usando el Scanner. Importante: para usar el método nextLine() de Scanner el mensaje debe tener un salto de línea al final "\n" , sino debe usarse next().
    – Lobos
    el 26 jul. 2020 a las 22:40
  • gracias por tu código. Pero al ejecutarlo y conectarme al servidor al parecer recibo un paquete, pero solo una vez y no en forma de byte. Me aparecen signos y símbolos que no pueden ser interpretados (rombo con un signo de pregunta). El servidor envia los bytes que se forman de esta manera: github.com/AresChat/sb0t/blob/… (en el método Public se puede ver de qué manera están formados. Estoy tratando de recibir el paquete MSG_CHAT_SERVER_PUBLIC. el 30 jul. 2020 a las 13:50
  • Tengo que recibir una cantidad desconocida de bytes, un byte que es null y otra cantidad desconocida de bytes: uruguayos-xtremos2011.blogspot.com/p/… el 30 jul. 2020 a las 13:52
  • Muy bien. Con esa información actualicé la respuesta con una posible solución más cercana al problema. El cliente recibe un mensaje donde los primeros 2 bytes son la longitud del mensaje, 1 byte para el protocolo MSG_CHAT_SERVER_PUBLIC = 10, y el resto es la data. De la data se extrae el username y el mensaje.
    – Lobos
    el 30 jul. 2020 a las 17:04

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.