Unable to read data from InputStream

I'm trying to learn java socket programming, but I have a trouble with the read function of InputStream. At first, I created a socket to connect to the server. After the connection is established, the server then send back the message that "the connection is established" and the read function is work fine. Then I tried to send byte message to the server, but I can't read the data from the InputStream because my program is stuck at "in.read(buf)" line. Could anyone point me out how can I solve this issue.

Socket client = new Socket("xxx.xxx.xxx.xxx", 45000);
    InputStream in = client.getInputStream();
    OutputStream out = client.getOutputStream();
    for (int i = 0; i < 5; i++) {
        byte[] buf = new byte[1024];
        int data_size = in.read(buf);
        String msg = "";
        for (int j = 0; j < data_size; j++) {
            msg += String.valueOf((char) buf[i]);
        }
        System.out.println(msg);
        out.write(65);
        out.flush();
    }

InputStream.read() is a blocking call. Given the code you have provided, you are reading from the socket before writing to the socket so you will block on the first read forever. Or at least until the timeout.


@Peter Could be right. Also, closing the streams after their usage might help avoiding unexpected issues.

链接地址: http://www.djcxy.com/p/78378.html

上一篇: PHP套接字写入然后读取是阻塞套接字

下一篇: 无法从InputStream读取数据