Java NIO Test Case
package org.zwl.test.nio; import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger; /**
* @author zhenweiliu created on 3/6/14
*/
public class NioServer { private Selector selector;
private AtomicInteger acceptCount = new AtomicInteger(0);
private AtomicInteger readCount = new AtomicInteger(0);
private AtomicInteger writeCount = new AtomicInteger(0); public NioServer(int port) throws IOException {
ServerSocketChannel ssc = ServerSocketChannel.open(); // 使用默认的selector provider生成一个channel
ssc.configureBlocking(false); // 设置为非阻塞模式
ssc.bind(new InetSocketAddress(port)); // 绑定到端口
selector = Selector.open();
ssc.register(selector, SelectionKey.OP_ACCEPT); // 将channel注册到selector, 并指定其兴趣集事件 while (selector.select() > 0) { // select()是个阻塞方法, 只有当selector中有已经准备好的事件的时候才会返回, 它返回已经准备好的事件数
for (SelectionKey key : selector.selectedKeys()) { // 遍历已经准备好的事件的key
selector.selectedKeys().remove(key);
if (key.isAcceptable()) {
System.out.println("Accept client " + acceptCount.incrementAndGet());
SocketChannel sc = ((ServerSocketChannel) key.channel()).accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
} else if (key.isReadable()) {
System.out.println("Read client " + readCount.incrementAndGet());
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer bb = ByteBuffer.allocate(1024);
bb.clear();
try {
while (sc.read(bb) > 0) {
bb.flip();
System.out.print(StandardCharsets.UTF_8.decode(bb));
bb.clear();
}
System.out.println();
} catch (IOException e) {
sc.close();
} if (key.isWritable()) {
System.out.println("Write client " + writeCount.incrementAndGet());
bb.clear();
bb.put("Hello Client".getBytes());
bb.flip();
try {
while (bb.hasRemaining()) {
sc.write(bb);
}
} catch (Exception e) {
sc.close();
}
}
}
}
}
} public static void main(String[] args) throws IOException {
new NioServer(8089);
}
}
package org.zwl.test.nio; import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.ExecutionException; import static java.nio.channels.SelectionKey.OP_CONNECT;
import static java.nio.channels.SelectionKey.OP_READ;
import static java.nio.channels.SelectionKey.OP_WRITE; /**
* @author zhenweiliu created on 3/6/14
*/
public class NioClient { public NioClient(String host, int port) throws Exception {
Selector selector = Selector.open();
SocketChannel sc = SocketChannel.open(new InetSocketAddress(host, port));
sc.configureBlocking(false);
SelectionKey sk = sc.register(selector, OP_CONNECT | OP_READ | OP_WRITE);
new ClientWriteThread(sk).start();
while (selector.select() > 0) {
for (SelectionKey key : selector.selectedKeys()) {
selector.selectedKeys().remove(key);
SocketChannel sc2 = (SocketChannel) key.channel();
if (key.isConnectable()) {
System.out.println("Connection established");
} else if (key.isReadable()) {
System.out.println("Read Server");
ByteBuffer bb = ByteBuffer.allocate(128);
bb.clear();
while (sc2.read(bb) > 0) {
bb.flip();
System.out.print(StandardCharsets.UTF_8.decode(bb));
bb.clear();
}
System.out.println();
}
}
}
} private static class ClientWriteThread extends Thread { private SelectionKey key; private Scanner scanner = new Scanner(System.in); public ClientWriteThread(SelectionKey key) {
this.key = key;
} @Override
public void run() {
while (key.isWritable()) {
String msg = scanner.nextLine();
ByteBuffer bb = ByteBuffer.allocate(msg.getBytes().length);
bb.clear();
bb.put(msg.getBytes());
bb.flip();
try {
while (bb.hasRemaining()) {
((SocketChannel) key.channel()).write(bb);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} public static void main(String[] args) throws Exception {
new NioClient("localhost", 8089); }
}
使用selector的好处在于
1. selector可以使用一个线程同时监听多个channel,他们的事件准备由系统通知, 类似于事件驱动, 不需要自己手动缓存所有chanel, 并while去轮询, 这样效率高
2. 他的read write方法都是非阻塞方法, 返回的是本次操作写入(或读取)成功的数据字节数
Java NIO Test Case的更多相关文章
- 源码分析netty服务器创建过程vs java nio服务器创建
1.Java NIO服务端创建 首先,我们通过一个时序图来看下如何创建一个NIO服务端并启动监听,接收多个客户端的连接,进行消息的异步读写. 示例代码(参考文献[2]): import java.io ...
- Five ways to maximize Java NIO and NIO.2--reference
Java NIO -- the New Input/Output API package-- was introduced with J2SE 1.4 in 2002. Java NIO's purp ...
- 【NIO】Java NIO之选择器
一.前言 前面已经学习了缓冲和通道,接着学习选择器. 二.选择器 2.1 选择器基础 选择器管理一个被注册的通道集合的信息和它们的就绪状态,通道和选择器一起被注册,并且选择器可更新通道的就绪状态,也可 ...
- java NIO详解
http://zalezone.cn/2014/09/17/NIO%E7%B2%BE%E7%B2%B9/ 1. 前言 我们在写java程序的时候,为了进行优化,把全部的精力用在了处理效率上,但是对IO ...
- Java NIO之选择器
1.简介 前面的文章说了缓冲区,说了通道,本文就来说说 NIO 中另一个重要的实现,即选择器 Selector.在更早的文章中,我简述了几种 IO 模型.如果大家看过之前的文章,并动手写过代码的话.再 ...
- android升级后错误:Unable to execute dex: java.nio.BufferOverflowException.Check
Android SDK Tools升级为22.3,Android SDK Platform-tools 升级为19后,编译工程出现错误: Unable to execute dex: java.nio ...
- IO的详细解释:It's all about buffers: zero-copy, mmap and Java NIO
There are use cases where data need to be read from source to a sink without modification. In code t ...
- Java NIO Files
Java NIO Files Files.exists() Files.createDirectory() Files.copy() Overwriting Existing Files Files. ...
- java NIO Buffer 详解(1)
1.java.io 最为核心的概念是流(stream),面向流的编程,要么输入流要么输出流,二者不可兼具: 2.java.nio 中拥有3个核心概念: Selector Channel, Buffe ...
随机推荐
- 008.MySQL-Keepalived搭配脚本02
vim /etc/keepalived/check_MySQL.sh #!/bin/sh #isok=$(sed -n '2p' /etc/keepalived/result.txt) isok=$( ...
- python基础下的数据结构与算法之链表
一.链表的定义 用链接关系显式表示元素之间顺序关系的线性表称为链接表或链表. 二.单链表的python实现 class Node(object): """定义节点&quo ...
- Sublime快速入门
在当前的互联网时代,任何程序语言和相关技术都只是实现互联网应用的一种手段,这也就造成了大量的互联网工程师长期与不同的语言.技术.系统环境.IDE等打交道.因此一个相对统一方便的IDE对于程序员来说显得 ...
- ApiPost自动化测试基础之:如何使用测试校验(测试用例)?
我们在<ApiPost的环境变量的定义和使用>和<ApiPost自动化测试基础之:接口参数依赖的情景处理>分别讲解了ApiPost环境变量的定义.使用以及基于环境变量的接口参数 ...
- odoo导入功能二开
原来有的导入功能相信很多小伙伴对其功能不是很满意,不过没关系,我们可以二开啊,把它的功能改造成你想要的样子,接下来让我们看看怎么办吧 例如我想把员工导入功能中添加上用户同步注册功能 首先,我要找到原模 ...
- poj 2253 最短路floyd **
题意:有两只青蛙和若干块石头,现在已知这些东西的坐标,两只青蛙A坐标和青蛙B坐标是第一个和第二个坐标,现在A青蛙想要到B青蛙那里去,并且A青蛙可以借助任意石头的跳跃,而从A到B有若干通路,问从A到B的 ...
- Codeforces Round #368 (Div. 2) B. Bakery 水题
B. Bakery 题目连接: http://www.codeforces.com/contest/707/problem/B Description Masha wants to open her ...
- javascript区域打印代码
这段代码是我从Highcharts的代码中改造出来的,非常感谢Highcharts的作者,先链上Highcharts的地址http://www.highcharts.com/,(Highcharts的 ...
- Redis "MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk"问题的解决(转)
今天第二次遇到Redis “MISCONF Redis is configured to save RDB snapshots, but is currently not able to persis ...
- 【Unity 3D】碰撞检测
在unity3d中,能检测碰撞发生的方式有两种, 碰撞器 触发器 概念: (一)碰撞器是一群组件,它包含了很多种类,比如:Box Collider,Capsule Collider等,这些碰撞 ...