NIO 使用的简单例子
来源:互联网 发布:易语言在线播放器源码 编辑:程序博客网 时间:2024/05/17 15:37
1.FileChannel
fileChannel 是阻塞的,不可以运行在非阻塞模式,因此不能被注册到 Selector 上
简单例子如下:
File f = new File("abcd"); File f2 = new File("abcd2"); try (RandomAccessFile accessFile = new RandomAccessFile(f, "r"); RandomAccessFile accessFile2 = new RandomAccessFile(f2, "rw"); FileChannel fileChannel = accessFile.getChannel(); FileChannel fileChannel2 = accessFile2.getChannel();) { fileChannel2.position(fileChannel2.size()); ByteBuffer buffer = ByteBuffer.allocate(128); while (fileChannel.read(buffer) > 0) { buffer.flip(); while (buffer.hasRemaining()) { fileChannel2.write(buffer); } buffer.clear(); System.out.println("------"); } }
RandomAccessFile中获取FileChannel,通过ByteBuffer可以从FileChannel中读取数据也可以向FileChannel写入数据,注意写数据时需要使用 while 循环,因为不能保证 ByteBuffer 一次性将数据全部写入.fileChannel.force(true)方法强制将内存数据同步到磁盘(boolean 参数表示是否将文件元数据写入(权限信息等)).注意ByteBuffer读写之间需要调用方法flip,切换读写模式
2.使用 Selector
只有非阻塞的 channel 才能注册到 selector 上,因此必须使用非阻塞 channel,此处使用 socketChannel 与 socketServerChannel 来做示范,示例代码如下:
客户端代码:
public class SocketNio{ private static Charset charset = Charset.forName("UTF-8"); private static int IO_LENGTH = 20; private static int BUFFER_SIZE = 128; private static int PORT = 8090; public static void main(String[] args) throws IOException { SocketChannel channel = SocketChannel.open(); channel.connect(new InetSocketAddress(PORT)); ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); @SuppressWarnings("resource") Scanner input = new Scanner(System.in); while (true) { String s = input.nextLine(); buffer.clear(); for (int i = 0; i < Math.ceil(s.length() / (double)IO_LENGTH); i++) { buffer.put(charset.encode(i * IO_LENGTH + IO_LENGTH > s.length() ? s.substring(i * IO_LENGTH) : s.substring(i * IO_LENGTH, i * IO_LENGTH + IO_LENGTH))); buffer.flip(); while (buffer.hasRemaining()) { channel.write(buffer); } buffer.clear(); } } }}
客户端仅仅实现了一个发送数据的功能
服务端代码如下:
public class SocketServerNIO{ private static Charset charset = Charset.forName("UTF-8"); private static int PORT = 8090; private static int BUFFER_SIZE = 128; public static void main(String[] args) throws IOException { ServerSocketChannel channel = ServerSocketChannel.open(); channel.bind(new InetSocketAddress(PORT)); channel.configureBlocking(false); final Selector selector = Selector.open(); channel.register(selector, SelectionKey.OP_ACCEPT); while (selector.select() > 0) { Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); if (key.isAcceptable()) { SocketChannel sc = ((ServerSocketChannel)key.channel()).accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); // 将sk对应的Channel设置成准备接受其他请求 key.interestOps(SelectionKey.OP_ACCEPT); } if (key.isReadable()) { // 获取该SelectionKey对应的Channel SocketChannel sc = (SocketChannel)key.channel(); ByteBuffer buff = ByteBuffer.allocate(BUFFER_SIZE); String content = ""; try { while (sc.read(buff) > 0) { buff.flip(); content += charset.decode(buff); buff.clear(); } System.out.println("读取的数据:" + content); key.interestOps(SelectionKey.OP_READ); } // 如果捕获到带sk对应的Channel出现了异常,即表明该Channel对应的Client出现了问题, // 所以从Selector中取消sk的注册 catch (IOException e) { keyIterator.remove(); key.cancel(); if (key.channel() != null) key.channel().close(); } } keyIterator.remove(); } } }}
服务端将 socketServerChannel 与每一个客户端连接的 socketChannel 均加入到 selector 监听,每当检测到有数据写入时,服务端就将写入数据打印出来,注意每个被注册的 channel 均被设置为非阻塞模式
阅读全文
0 0
- NIO 使用的简单例子
- NIO的简单例子
- NIO使用的例子
- NIO的简单使用
- NIO Socket传输的简单例子
- 【NIO】更简单的nio使用方式
- NIO 简单交互例子
- Java NIO 简单例子
- Java Nio简单例子
- Java NIO简单例子
- java nio 使用例子
- Java NIO例子——MINA的最简单模型
- Netty学习笔记<2>--简单的NIO例子
- java的nio例子
- 使用nio实现简单的httpServer
- nio selector简单使用
- 使用makefile的简单例子
- wxButton的简单使用例子
- 6-1
- Unique Binary Search Trees
- Spring集成Mybatis
- 完成端口 IOCP
- C++类定义对构造和析构的调用的区别
- NIO 使用的简单例子
- 微信公众测试号使用Java Spring MVC,接口配置token验证。
- php加密函数和解密函数,原字符串输出
- 有关极光推送的列子
- nagular1的summernote的使用总结
- C#期末大作业 消消乐
- 最方便的自定义带点击效果的圆角背景按钮
- 【Spring之旅】Spring学习常见问题汇总
- PHP 多进程和多线程的优缺点