关于BufferedReader readline 阻塞的问题

这两天在做socket通讯的一些东西

其中就用到了BufferedReader缓冲流,然而就是在传输数据时在服务端使用readline()读取时,一直读取不到,使用debug发现,readline是发生了阻塞

       这是api的解释    读取一个文本行。通过下列字符之一即可认为某行已终止:换行 ('\n')、回车 ('\r') 或回车后直接跟着换行。

 也就是说读取一行知道碰到换行符,或回车符,则认为此行已近读完了,接着返回,


  我把代码粘上来,有兴趣的同学自己测试下


public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ssk = new ServerSocket(9000);
// Socket sk;
//等待连接
//实现多个连接
while (true) {
Socket sk = ssk.accept();// 包含数据   
System.out.println("连接成功");
InputStream is = sk.getInputStream();

//这是我使用read方法读取 是没问题的
// byte [] b = new byte[1024];
// int x = is.read(b, 0, b.length);
// String str3 = new String(b,0,x);
// System.out.println(str3);


BufferedReader buff = new BufferedReader(new InputStreamReader(is));
String str = null;
while ((str = buff.readLine())!=null) {
System.out.println("---");
System.out.println(str);
}
System.out.println("是否发送数据回去");
Scanner sc = new Scanner(System.in);
String str1 = sc.next();
if("y".equals(str1)){
OutputStream os = sk.getOutputStream();
byte []byt = "javahello".getBytes();
os.write(byt);
os.close();
}else{
break;
}
is.close();
sk.close();
}
System.out.println("停止服务器");
}
}




public class Client {
 public  static Socket sk;
public static void main(String[] args) throws IOException {
Client c = new Client();
sk = new Socket("127.0.0.1",9000);
OutputStream os = sk.getOutputStream();
byte [] by = "下雨\n".getBytes();    //如果字符串不加\n   readline方法将一直阻塞 而                                     //read方法则不会出现阻塞的情况 
os.write(by, 0, by.length);//当把数据写过去之后,立马开启接受的线程
//开启一个接收的线程
TThread  td = c.new TThread();
td.start();
}
class TThread extends Thread{
//接受的是那个对象的  
@Override
public void run(){
try {
while(true){
InputStream is = sk.getInputStream();
BufferedReader buff = new BufferedReader(new InputStreamReader(is));
String str = null;
while ((str = buff.readLine())!=null) {
System.out.println(str);
}
// is.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值