Java NIO 初学

刚开始学习java nio开发,写了个简单的例子,使用NIO 实现阻塞的发送接收数据,但是发现客户端一直没有接受到数据:

@Test
	public void Server() throws IOException{
		ServerSocketChannel sChannel = ServerSocketChannel.open();
		sChannel.bind(new InetSocketAddress(9010));
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		String msg = "abcdef21a下小";
		System.out.println(msg.getBytes().length);
		byteBuffer.put(msg.getBytes());
		System.out.println("存数据:capacity:"+byteBuffer.capacity());
		System.out.println("存数据:limit:"+byteBuffer.limit());
		System.out.println("存数据:position:"+byteBuffer.position());
		System.out.println("服务端已启动,等待客户端连接");
		SocketChannel channel = sChannel.accept();
		System.out.println("客户端已连接,开始发送数据");
		byteBuffer.flip();
		channel.write(byteBuffer);
		channel.close();
		sChannel.close();
	}

@Test
	public void client() throws IOException{
		SocketChannel channel = SocketChannel.open();
		channel.connect(new InetSocketAddress("localhost", 9010));
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		System.out.println("客户端启动,连接上服务端,准备接受数据");
		int p =0;
		while((p=channel.read(byteBuffer))!=-1){
			System.out.println("读了几个:"+p);
			System.out.println("读后:capacity:"+byteBuffer.capacity());
			System.out.println("读后:limit:"+byteBuffer.limit());
			System.out.println("读后:position:"+byteBuffer.position());
			System.out.println("读后:remaining:"+byteBuffer.remaining());
			byteBuffer.flip();
			byte[] bts = new byte[byteBuffer.remaining()];
			byteBuffer.get(bts);
			System.out.println("客户端接收到数据:"+new String(bts));
			byteBuffer.clear();
		}
		
		
		channel.close();
	}
	

只是简单的学习,代码比较简单,当在服务端和客户端加了对应的byteBuffer.filp()之后,才能实
现服务端发送与客户端接收,其中原理,这个例子主要是立即ByteBuffer的3个重要的标识,limit、
capacity、position (限制大小,容量,当前位置),新建ByteBuffer时 limit与capacity一样,
positon=0,当使用put放入数据时
 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值