关于字节流从socket里面读数据的问题?

xuhua205 2009-04-20 07:03:18

DataInputStream in = new DataInputStream(socket.getInputStream());
StringBuilder sb = new StringBuilder();
for (int c = in.read(); c != -1; c = in.read()) {
System.out.print((char)c);
}
System.out.println("响应信息为:" + sb);


上面一段代码中是从socket中读取数据,比如socket中的数据为0123456,那么进入for循环之后就会读取这几个值,最终打印0123456
但是现在的问题是:
程序会在打印完6之后一直堵塞在in.read()这里,出不来 不会执行下面的 System.out.println("响应信息为:" + sb); 这句话
想问问大家,怎样才能让程序跳出来,在实际问题中,socket中的值是不确定的



...全文
188 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhaodalong 2009-05-12
  • 打赏
  • 举报
回复
Java 深度路过者!
小坏蛋rubys 2009-05-01
  • 打赏
  • 举报
回复
Java 深度探索者 QQ群:65670864
fashi1000 2009-04-23
  • 打赏
  • 举报
回复
for (int c = in.read(); c != -1; c = in.read()) 连接断开前会一直等待接受的。
有两种方式
另一端在发送完数据后断开连接,这种叫短连接
还有一种长连接的,是双方 约定数据包结束标记,当程序读到结束标记的时候表示这次的数据发送结束,就break跳出循环
CRC622 2009-04-22
  • 打赏
  • 举报
回复
温习了
jinxfei 2009-04-20
  • 打赏
  • 举报
回复
DataInputStream in = new DataInputStream(socket.getInputStream());
StringBuilder sb = new StringBuilder();
for (int c = in.read(); c != -1; c = in.read()) {
System.out.print((char)c);
if (in.available()<=0){
break;
}
}
System.out.println("响应信息为:" + sb);
yangqidong 2009-04-20
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 yangqidong 的回复:]
for (int c = in.read(); c != -1; c = in.read()) {
        System.out.print((char)c);
    }

改成
int c;
while((c = in.read())!=-1){
  System.out.print((char)c);
}
[/Quote]

再仔细看,两种写法是一样的,晕...
zhangpeixv 2009-04-20
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 yangqidong 的回复:]
for (int c = in.read(); c != -1; c = in.read()) {
System.out.print((char)c);
}

改成
int c;
while((c = in.read())!=-1){
System.out.print((char)c);
}
[/Quote]
我觉得跟上面这个也是有关系
因为我一直用的while也没有出过错啊
关键是for的处理
呵呵让它跳出来
可以让socket,setTimeOut啊
不过你这个应该不是这里的问题啊
ty_tarena_pger 2009-04-20
  • 打赏
  • 举报
回复
1>不能把客户端每次读过来的数据一次性赋值给一个String吗?然后现根据这个String便利
2>实再不行把DataInputStream换成BufferedReader吧(我觉得DataInputStream没BufferedReader好用)
yangqidong 2009-04-20
  • 打赏
  • 举报
回复
for (int c = in.read(); c != -1; c = in.read()) {
System.out.print((char)c);
}

改成
int c;
while((c = in.read())!=-1){
System.out.print((char)c);
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧