IO流中while 和if的区别

BIO服务端:

public class BIOServer {
	
	ServerSocket server;
	//服务器
	public BIOServer(int port){
		try {
			//把Socket服务端启动
			server = new ServerSocket(port);
			System.out.println("BIO服务已启动,监听端口是:" + port);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 开始监听,并处理逻辑
	 * @throws IOException 
	 */
	public void listener() throws IOException{
		//死循环监听
		while(true){
			//虽然写了一个死循环,如果一直没有客户端连接的话,这里一直不会往下执行
			Socket client = server.accept();//等待客户端连接,阻塞方法
			
			//拿到输入流,也就是乡村公路
			InputStream is = client.getInputStream();
			
			//缓冲区,数组而已
			byte [] buff = new byte[1024];
			int len = is.read(buff);
			//只要一直有数据写入,len就会一直大于0
			if(len > 0){
				String msg = new String(buff,0,len);
				System.out.println("收到" + msg);
			}
//
//			while (len != -1){
//				String msg = new String(buff,0,len);
//				System.out.println("收到" + msg);
//			}
		}
	}
	
	
	public static void main(String[] args) throws IOException {
		new BIOServer(8081).listener();
	}
	
}

 

BIO客户端:

public class BIOClient2 {

	public static void main(String[] args) throws UnknownHostException, IOException {

		try{
			
			
			//开一条乡村公路
			Socket client = new Socket("localhost", 8081);
			//输出流通道打开
			OutputStream os = client.getOutputStream();
			//产生一个随机的字符串,UUID
			String name = UUID.randomUUID().toString();
			
			//发送给服务端
			os.write(name.getBytes());
			os.close();
			client.close();
			
		}catch(Exception e){
			
		}
	}
		
	
}

 

server端: 使用

if(len > 0){
   String msg = new String(buff,0,len);
   System.out.println("收到" + msg);
}

客户端发送一次,则服务器只打印一次。

 

使用:while时

while (len != -1){
   String msg = new String(buff,0,len);
   System.out.println("收到" + msg);
}

客户端发送一次,则服务器会一直循环打印传输的uuid

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值