Socket Programming : Inputstream Stuck in loop - read() always return 0

Posted by Atom Skaa ska Hic on Stack Overflow See other posts from Stack Overflow or by Atom Skaa ska Hic
Published on 2011-06-29T07:26:43Z Indexed on 2011/06/29 8:22 UTC
Read the original article Hit count: 151

Filed under:
|

Server side code

public static boolean sendFile() {
        int start = Integer.parseInt(startAndEnd[0]) - 1;
        int end = Integer.parseInt(startAndEnd[1]) - 1;
        int size = (end - start) + 1;

        try {
            bos = new BufferedOutputStream(initSocket.getOutputStream());
            bos.write(byteArr,start,size);
            bos.flush();
            bos.close();
            initSocket.close();
            System.out.println("Send file to : " + initSocket);
        } catch (IOException e) {
            System.out.println(e.getLocalizedMessage());
            disconnected();
            return false;
        }

        return true;
    }

Client Side

public boolean receiveFile() {
        int current = 0;

        try {
            int bytesRead = bis.read(byteArr,0,byteArr.length);
            System.out.println("Receive file from : " + client);
            current = bytesRead;
            do {
                 bytesRead =
                 bis.read(byteArr, current, (byteArr.length-current));
                 if(bytesRead >= 0) current += bytesRead;
            } while(bytesRead != -1);
            bis.close();
            bos.write(byteArr, 0 , current);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            System.out.println(e.getLocalizedMessage());
            disconnected();
            return false;
        }
        return true;

    }

Client side is multithreading,server side not use multithreading. I just paste some code that made problem if you want see all code please tell me.

After I debug the code, I found that if I set max thread to any and then the first thread always stuck in this loop. That bis.read(....) always return 0. Although, server had close stream and it not get out of the loop. I don't know why ... But another threads are work correctly.

do {
     bytesRead =
     bis.read(byteArr, current, (byteArr.length-current));
     if(bytesRead >= 0) current += bytesRead;
} while(bytesRead != -1);

© Stack Overflow or respective owner

Related posts about java

Related posts about socket-proramming