Reading packets from a server with Java sockets

1

I am developing a program for reading packages sent by computers to a server that has the port 7779 enabled to receive this data. For this I use sockets from Java .

The problem I have is that I open the port, read the information, but after a moment it stops receiving the same. Apparently it is hanging, I know that data is still coming because I check it with tcpflow .

The code I use is the following.

public static void main(String[] args) {

    iniciarArchivoLog();
    iniciarConexionBaseDatos();

    procesarTramas();
}
private static void procesarTramas(){
    char caracter;
    byte[] bytes;
    InputStream stream = null;
    int bytesLeidos;
    Integer puerto;
    ServerSocket serverSocket;
    Socket socket;
    String hexadecimal, cadena = "";

    puerto = Integer.valueOf(obtenerPropiedad("socket.port"));

    try {
        serverSocket = new ServerSocket(puerto);
        socket = serverSocket.accept();
        stream = socket.getInputStream();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    bytesLeidos = 0;
    bytes = new byte[1];            

    while(true){
        try {
            bytesLeidos = stream.read();

            consolaLogger.info(String.valueOf(bytesLeidos));
            caracter = convertirEnteroACaracter(bytesLeidos);
            cadena += String.valueOf(caracter);
            if(caracter == '@'){
                consolaLogger.info(cadena);
                cadena = "@";
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
private static char convertirEnteroACaracter(int valor){
    char caracter;

    caracter = (char) valor;

    return caracter;
}

I use the read() method to read the integer from stream , and then convert it to character to print it, after some impressions, it does not print anymore.

    
asked by Chris. R. 28.01.2017 в 23:45
source

1 answer

0

You declared bytes as a byte array and you use bytesLeidos , but in your code you use another way to read data from a stream. It seems to me that you used example code or specification of a task and did not apply it well. If you want to work with bytes, you should do something like this:

bytes = new byte[1024]    

while(bytesLeidos!=-1){
        bytes = new byte[stream.available()];
        bytesLeidos = stream.read(bytes);
        for (int i = 0; i<bytesLeidos;i++){
             // has lo que quieras con bytes[i]
        }
}
// si bytesLeidos == -1, el InputStream llegó a su fin
    
answered by 29.01.2017 в 00:11