欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java NIO 初学 javanio 

程序员文章站 2022-07-15 13:57:25
...

刚开始学习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放入数据时
 

 

 

相关标签: java nio