日期:2014-05-20  浏览次数:20731 次

java socket io
代码:

Socket client = 创建实例;
InputStream is = client.getInputStream();
DataInputStream dis = new DataInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = -1;
while ((len = dis.read(buf, 0, 1024)) != -1) {
  baos.write(buf, 0, len);
 }

在实际当中,代码会在while ((len = dis.read(buf, 0, 1024)) != -1)处卡死,导致程序一直等待,请问大家这是什么原因,如何解决?

------解决方案--------------------
个人认为:不是卡死,是线程阻塞。java io的jni就这样实现,只要流无到末端,调用read方法无数据,就一直阻塞。也是我们想要的结果。如要你的继续程序运行,只要的在scocket的另一端写入数据,你的socket就不会阻塞。
------解决方案--------------------
这个是因为读取不到服务器端的数据流而导致read方法一直堵塞,跟用不用nio没关系
估计是你的服务器端发送来的数据流在read执行之前!或者试试这样行么:
Java code

Socket client = 创建实例;
InputStream is = client.getInputStream();
DataInputStream dis = new DataInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = -1;
while(true){//[color=#FF0000]循环监听服务器端发送来的数据流[/color]
while ((len = dis.read(buf, 0, 1024)) != -1) {
  baos.write(buf, 0, len);
 }
}