Java NIO 初学 javanio
程序员文章站
2022-07-15 13:57:07
...
刚开始学习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放入数据时
上一篇: 《将博客搬至CSDN》
下一篇: [转] Create a Java Keystore (.JKS) from Let's Encrypt Certificates httpspkcs12opensslkeystore
推荐阅读
-
JAVA-NIO之Socket/ServerSocket Channel(详解)
-
JAVA-4NIO之Channel之间的数据传输方法
-
Java NIO框架Netty简单使用的示例
-
浅谈Java中BIO、NIO和AIO的区别和应用场景
-
JAVA-4NIO之Channel之间的数据传输方法
-
JAVA-NIO之Socket/ServerSocket Channel(详解)
-
Java文件读写IO/NIO及性能比较详细代码及总结
-
初学java常用开发工具介绍
-
JDK1.7 之java.nio.file.Files 读取文件仅需一行代码实现
-
Java NIO Path接口和Files类配合操作文件的实例