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,在系 ...
随机推荐
- Android中的BroadCast静态注册与动态注册
1.静态注册 新建MyBroadcast类继承BroadcastReceiver,实现onReceive方法 /** * Author:JsonLu * DateTime:2015/9/21 16:4 ...
- Volley框架使用(POST)
需要在MyApplication(继承Application)中配置; public static RequestQueue requestQueue; @Override public void o ...
- Python 文件的IO
对文件的操作 #coding=utf-8 #!user/bin/python import os #基本操作和写入文件 fo = open("test2.py",'wb') pri ...
- 系统spt_values表--生成时间方便left join
时间处理我给你提供一个思路 系统有个spt_values表,可以构造一整个月的日期,然后左连接你统计好的数据,用CTE表构造多次查询 spt_values的超级经典的应用 http://www. ...
- JNI测试-java调用c算法并返回java调用处-1到20阶乘的和
一,java端: 定义native方法, 'public native long factorial(int n);', 该方法用c/c++实现,计算'1到20阶乘的和',参数中'int n'是前n项 ...
- 利用后缀数组(suffix array)求最长公共子串(longest common substring)
摘要:本文讨论了最长公共子串的的相关算法的时间复杂度,然后在后缀数组的基础上提出了一个时间复杂度为o(n^2*logn),空间复杂度为o(n)的算法.该算法虽然不及动态规划和后缀树算法的复杂度低,但其 ...
- hdu1230火星A+B (大数题)
Problem Description 读入两个不超过25位的火星正整数A和B,计算A+B.需要注意的是:在火星上,整数不是单一进制的,第n位的进制就是第n个素数.例如:地球上的10进制数2,在火星上 ...
- 跟我学android-常用控件之 TextView
TextView 是Android文本控件,用于显示文字. 我们先看一看TextView的结构(developer.android.com) 从这里我们可以得知,TextView是View的子类,他有 ...
- css命名为何不推荐使用下划线_
一直习惯了在命名CSS样式名时使用下划线“_”做为单词的分隔符,这也是在写JS时惯用的写法. 用过CSS hack的朋友应该知道,用下划线命名也是一种hack,如使用“_style”这样的命名,可以让 ...
- iscroll.js & flipsnap.js
两个js都可以用做手机的滑动框架iscroll.js功能更多flipsnap.js应该只能水平滑动. iscroll.js介绍http://iiunknown.gitbooks.io/iscroll- ...