NIO Socket非阻塞模式
NIO主要原理和适用
NIO 有一个主要的类Selector,这个类似一个观察者,只要我们把需要探知的socketchannel告诉Selector,我们接着做别的事情,当有 事件发生时,他会通知我们,传回一组SelectionKey,我们读取这些Key,就会获得我们刚刚注册过的socketchannel,然后,我们从 这个Channel中读取数据,放心,包准能够读到,接着我们可以处理这些数据。
Selector内部原理实际是在做一个对所注册的channel的轮询访问,不断的轮询(目前就这一个算法),一旦轮询到一个channel有所注册的事情发生,比如数据来了,他就会站起来报告,交出一把钥匙,让我们通过这把钥匙来读取这个channel的内容。
jdk供的无阻塞I/O(NIO)有效解决了多线程服务器存在的线程开销问题,但在使用上略显得复杂一些。在NIO中使用多线程,主要目的已不是为了应对 每个客户端请求而分配独立的服务线程,而是通过多线程充分使用用多个CPU的处理能力和处理中的等待时间,达到提高服务能力的目的。
这段时间在研究NIO,写篇博客来记住学过的东西。还是从最简单的Hello World开始,client多线程请求server端,server接收client的名字,并返回Hello! +名字的字符格式给client。当然实际应用并不这么简单,实际可能是访问文件或者数据库获取信息返回给client。非阻塞的NIO有何神秘之处?
代 码:
1)server端代码
- public class HelloWorldServer {
- static int BLOCK = 1024;
- static String name = "";
- protected Selector selector;
- protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);
- protected CharsetDecoder decoder;
- static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();
- public HelloWorldServer(int port) throws IOException {
- selector = this.getSelector(port);
- Charset charset = Charset.forName("GB2312");
- decoder = charset.newDecoder();
- }
- // 获取Selector
- protected Selector getSelector(int port) throws IOException {
- ServerSocketChannel server = ServerSocketChannel.open();
- Selector sel = Selector.open();
- server.socket().bind(new InetSocketAddress(port));
- server.configureBlocking(false);
- server.register(sel, SelectionKey.OP_ACCEPT);
- return sel;
- }
- // 监听端口
- public void listen() {
- try {
- for (;;) {
- selector.select();
- Iterator iter = selector.selectedKeys().iterator();
- while (iter.hasNext()) {
- SelectionKey key = (SelectionKey) iter.next();
- iter.remove();
- process(key);
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- // 处理事件
- protected void process(SelectionKey key) throws IOException {
- if (key.isAcceptable()) { // 接收请求
- ServerSocketChannel server = (ServerSocketChannel) key.channel();
- SocketChannel channel = server.accept();
- //设置非阻塞模式
- channel.configureBlocking(false);
- channel.register(selector, SelectionKey.OP_READ);
- } else if (key.isReadable()) { // 读信息
- SocketChannel channel = (SocketChannel) key.channel();
- int count = channel.read(clientBuffer);
- if (count > 0) {
- clientBuffer.flip();
- CharBuffer charBuffer = decoder.decode(clientBuffer);
- name = charBuffer.toString();
- // System.out.println(name);
- SelectionKey sKey = channel.register(selector,
- SelectionKey.OP_WRITE);
- sKey.attach(name);
- } else {
- channel.close();
- }
- clientBuffer.clear();
- } else if (key.isWritable()) { // 写事件
- SocketChannel channel = (SocketChannel) key.channel();
- String name = (String) key.attachment();
- ByteBuffer block = encoder.encode(CharBuffer
- .wrap("Hello !" + name));
- channel.write(block);
- //channel.close();
- }
- }
- public static void main(String[] args) {
- int port = 8888;
- try {
- HelloWorldServer server = new HelloWorldServer(port);
- System.out.println("listening on " + port);
- server.listen();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
2)client端代码
- public class HelloWorldClient {
- static int SIZE = 10;
- static InetSocketAddress ip = new InetSocketAddress("localhost", 8888);
- static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();
- static class Message implements Runnable {
- protected String name;
- String msg = "";
- public Message(String index) {
- this.name = index;
- }
- public void run() {
- try {
- long start = System.currentTimeMillis();
- //打开Socket通道
- SocketChannel client = SocketChannel.open();
- //设置为非阻塞模式
- client.configureBlocking(false);
- //打开选择器
- Selector selector = Selector.open();
- //注册连接服务端socket动作
- client.register(selector, SelectionKey.OP_CONNECT);
- //连接
- client.connect(ip);
- //分配内存
- ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);
- int total = 0;
- _FOR: for (;;) {
- selector.select();
- Iterator iter = selector.selectedKeys().iterator();
- while (iter.hasNext()) {
- SelectionKey key = (SelectionKey) iter.next();
- iter.remove();
- if (key.isConnectable()) {
- SocketChannel channel = (SocketChannel) key
- .channel();
- if (channel.isConnectionPending())
- channel.finishConnect();
- channel
- .write(encoder
- .encode(CharBuffer.wrap(name)));
- channel.register(selector, SelectionKey.OP_READ);
- } else if (key.isReadable()) {
- SocketChannel channel = (SocketChannel) key
- .channel();
- int count = channel.read(buffer);
- if (count > 0) {
- total += count;
- buffer.flip();
- while (buffer.remaining() > 0) {
- byte b = buffer.get();
- msg += (char) b;
- }
- buffer.clear();
- } else {
- client.close();
- break _FOR;
- }
- }
- }
- }
- double last = (System.currentTimeMillis() - start) * 1.0 / 1000;
- System.out.println(msg + "used time :" + last + "s.");
- msg = "";
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) throws IOException {
- String names[] = new String[SIZE];
- for (int index = 0; index < SIZE; index++) {
- names[index] = "jeff[" + index + "]";
- new Thread(new Message(names[index])).start();
- }
- }
- }
NIO Socket非阻塞模式的更多相关文章
- Java NIO Socket 非阻塞通信
相对于非阻塞通信的复杂性,通常客户端并不需要使用非阻塞通信以提高性能,故这里只有服务端使用非阻塞通信方式实现 客户端: package com.test.client; import java.io. ...
- 看到关于socket非阻塞模式设置方式记录一下。
关于socket的阻塞与非阻塞模式以及它们之间的优缺点,这已经没什么可言的:我打个很简单的比方,如果你调用socket send函数时: 如果是阻塞模式下: send先比较待发送数据的长度len和套接 ...
- JAVA NIO使用非阻塞模式实现高并发服务器
参考:http://blog.csdn.net/zmx729618/article/details/51860699 https://zhuanlan.zhihu.com/p/23488863 ht ...
- JAVA基础知识之网络编程——-基于NIO的非阻塞Socket通信
阻塞IO与非阻塞IO 通常情况下的Socket都是阻塞式的, 程序的输入输出都会让当前线程进入阻塞状态, 因此服务器需要为每一个客户端都创建一个线程. 从JAVA1.4开始引入了NIO API, NI ...
- IO通信模型(二)同步非阻塞模式NIO(NonBlocking IO)
同步非阻塞模式(NonBlocking IO) 在非阻塞模式中,发出Socket的accept()和read()操作时,如果内核中的数据还没有准备好,那么它并不会阻塞用户进程,而是立刻返回一个信息.也 ...
- UDP socket 设置为的非阻塞模式
UDP socket 设置为的非阻塞模式 Len = recvfrom(SocketFD, szRecvBuf, sizeof(szRecvBuf), MSG_DONTWAIT, (struct so ...
- socket异步通信-如何设置成非阻塞模式、非阻塞模式下判断connect成功(失败)、判断recv/recvfrom成功(失败)、判断send/sendto
socket异步通信-如何设置成非阻塞模式.非阻塞模式下判断connect成功(失败).判断recv/recvfrom成功(失败).判断send/sendto 博客分类: Linux Socket s ...
- Socket 阻塞模式和非阻塞模式
阻塞I/O模型: 简介:进程会一直阻塞,直到数据拷贝 完成 应用程序调用一个IO函数,导致应用程序阻塞,等待数据准备好. 如果数据没有准备好,一直等待….数据准备好了,从内核拷贝到用户空间,IO函数返 ...
- Socket阻塞模式和非阻塞模式的区别
简单点说: 阻塞就是干不完不准回来, 非组赛就是你先干,我现看看有其他事没有,完了告诉我一声 我们拿最常用的send和recv两个函数来说吧... 比如你调用send函数发送一定的Byte,在系 ...
随机推荐
- My.Ioc 代码示例——注册项的注销和更新
当您需要从 Ioc 容器中注销/删除一个注册项的时候,您会怎么做呢? 有人曾经在 stackoverflow 上提问“如何从 Unity 中注销一个注册项”.对于这个问题,有人的回答是“有趣.你为什么 ...
- 关于uploadify 没有显示进度条!!!!
如果你也弄了很久不知道为什么不出现上传进度条!,那就一定要看这里了! 我注释了 queueID 属性后 就出现了!!!!! 就是这么简答! //添加界面的附件管理 $('#file_upload'). ...
- jquery get checkbox inside element(td).
<td id="skill"><input name="skill" type="checkbox" value=&quo ...
- hdu 3371 Connect the Cities (最小生成树Prim)
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=3371 题目不难 稍微注意一下 要把已经建好的城市之间的花费定义为0,在用普通Prim算法就可以了:我没 ...
- CentOS6.5安装LAMP环境APACHE的安装
1.卸载apr.apr-util [root@centos6 LAMP]# yum remove apr apr-util 2.编译安装apr-1.5.1.tar.gz [root@centos6 L ...
- html form <label>标签基础语法结构与使用案例教程(转载)
在表单布局中会遇到label标签的使用,label没有任何样式效果,有触发对应表单控件功能.比如我们点击单选按钮或多选框前文字对应选项就能被选中,这个就是对文字加了<label>标签实现. ...
- jqgrid设置单元格数据
$("#gridid").jqGrid('setCell',rowid,icol,data); rowid为行ID,jqgrid内置的那个,从1开始 icol为列索引,从0开始, ...
- 2.2.5 NIO.2 Path 和 Java 已有的 File 类
NIO与IO交互 toPath() File -- Path toFile() Path -- File Demo: import java.io.File; import java.nio.file ...
- [转]JS继承的5种实现方式
参考链接: http://yahaitt.iteye.com/blog/250338 虽说书上都讲过继承的方式方法,但这些东西每看一遍都多少有点新收获,所以单独拿出来放着. 1. 对象冒充 funct ...
- iPhone 被同步到 Mac上后 如果不希望更新到Mac上在哪里删除?
前往文件夹 /Users/用户名/Library/Application Support/MobileSync 直接删除 就行了(同时要倾倒废纸篓). 目前iPhone链接Mac 后 不让 ...