bellszhu 发表于 2012-09-07 11:57

in.read()最后in.read(buf)都阻塞

服务器端应该是用.net写的

我客户端去读取数据

代码段1:BufferedReader in = new BufferedReader(new InputStreamReader(
                                socket.getInputStream()));
                int n = 0;
                while ((n = in.read()) > 0) {
                        char c = (char)n;
                        System.out.print((char) n);
                }
                System.out.println("end");代码段2:DataInputStream in = new DataInputStream(socket.getInputStream());
                byte[] buf = new byte;
                int len = 0;
                while ((len = in.read(buf)) != -1) {
                        String text = new String(buf, 0, len);
                        System.out.print(text);
                }这两段代码都能读取到服务端发来的数据
但是最后都会阻塞,程序不能结束!!
应该怎么处理呢?让程序读完数据后 退出程序??

dengxiayehu 发表于 2012-09-07 13:23

若是服务器端的socket流没有关闭动作,那么客户端采用这种读取方式当然会阻塞啊,
因为它并不知道应该什么时候读取结束。

可以考虑两边的传输建立于协议之上,服务器告诉客户端可以读多少内容,客户端读够
了就可以自行break了。
页: [1]
查看完整版本: in.read()最后in.read(buf)都阻塞