Read bytes from a socket in java

0

I'm trying to make a java server that reads bytes from the socket.

The problem I have here is that the function read() returns me -1 and this can be due to the fact that the connection is closed.

I do not know which is the problem by which the connection is closed. What I do in the main class is:

int port = -1;
ServerSocket socket = new ServerSocket(0);
port = socket.getLocalPort();
th r = new th(socket);
r.start();

In the class that implements the thread I have the following:

public class th extends Thread  {
    public static ServerSocket sc;
    public static byte[] buffer = new byte[256];
    int p;

    public th(){
        sc = null;
    }

    public th (ServerSocket userSC){
        sc = userSC;
    }

    public void run() {
        System.out.println("En la clase TH");
        Socket serverAddr;
        boolean condicion = true;
        DataInputStream in;

    for (p = 0; p < 256; p++) System.out.print(buffer[p] + " ");
        try {
            serverAddr = sc.accept();
            in = new DataInputStream(serverAddr.getInputStream());

            in.read(buffer);
            for (p = 0; p < 256; p++) System.out.print(buffer[p] + " ");
            int a = in.read(buffer);
            if (a == -1){
               Ssytema.out.println("ERROR");
            }
            for (p = 0; p < 256; p++) System.out.print(buffer[p] + " ");
            String res = new String(buffer);
            System.out.println(res);
            System.out.println("NO ESPERA");
            serverAddr.close();
        }
        catch (IOException e){
            System.err.println("Error creando socket");
        }
    }
}
    
asked by Mauricio Arias Olave 06.04.2017 в 09:53
source

0 answers