dimanche 26 juin 2016

While loop stops with operations on Input/Output streams

lately I'm having many problems with InputStreams and OutputStreams. It seems that opearting on the streams stop the application from running.

Socket socket;
InputStream in;
OutputStream out;

try {
    socket = new Socket("192.168.1.25", 8888);

    in = socket.getInputStream();
    out = socket.getOutputStream();
} catch (IOException ex) {
    ex.printStackTrace();
}

while (true) {
        try {
            if (in.available() > 0) {
                switch (in.read()) {
                    case 'u0011':
                        System.out.println("NOT ALREADY GOT ID");
                        clientID = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8));
                        System.out.println("GOT ID " + clientID);
                        break;
                    case 'u001c':
                        System.out.println("Receiving...");

                        byte[] bytes = ByteStreams.toByteArray(in);
                        System.out.println("bytes.length = " + bytes.length);

                        Files.write(bytes, new File(Environment.DIRECTORY_DOWNLOADS + "file.mp3"));
                        System.out.println("I received a file");
                        break;
                    case 'u0002':
                        System.out.println("I received: " + CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)));
                        break;
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

So, what exactly happens is that when 'u0011' char is sent along with the ID, the application seems to stop (while loop break) on reading the ID from the stream. Infact, 'NOT ALREADY GOT ID' gets printed but the ID itsef not. I've already tried both Guava (this code) and Commons IO from Apache, but I got the same problem.

Aucun commentaire:

Enregistrer un commentaire