堵塞IO实现:

public class PlainEchoServer {
public void serve(int port) throws IOException {
final ServerSocket socket = new ServerSocket(port);
try {
while (true) {
final Socket clientSocket = socket.accept();
System.out.println("Accepted connection from " + clientSocket);
new Thread(new Runnable() {
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(
clientSocket.getOutputStream(), true);
while (true) {
writer.println(reader.readLine());
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
try {
clientSocket.close();
} catch (IOException ex) {
// ignore on close
}
}
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

非堵塞IO(NIO)实现:

public class PlainNioEchoServer {
public void serve(int port) throws IOException {
System.out.println("Listening for connections on port " + port);
ServerSocketChannel serverChannel = ServerSocketChannel.open();
ServerSocket ss = serverChannel.socket();
InetSocketAddress address = new InetSocketAddress(port);
ss.bind(address);
serverChannel.configureBlocking(false);
Selector selector = Selector.open();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
try {
selector.select();
} catch (IOException ex) {
ex.printStackTrace();
// handle in a proper way
break;
}
Set readyKeys = selector.selectedKeys();
Iterator iterator = readyKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
iterator.remove();
try {
if (key.isAcceptable()) {
ServerSocketChannel server = (ServerSocketChannel) key
.channel();
SocketChannel client = server.accept();
System.out
.println("Accepted connection from " + client);
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_WRITE
| SelectionKey.OP_READ,
ByteBuffer.allocate(100));
}
if (key.isReadable()) {
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer output = (ByteBuffer) key.attachment();
client.read(output);
}
if (key.isWritable()) {
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer output = (ByteBuffer) key.attachment();
output.flip();
client.write(output);
output.compact();
}
} catch (IOException ex) {
key.cancel();
try {
key.channel().close();
} catch (IOException cex) {
}
}
}
}
}
}

异步IO(NIO.2)实现:

public class PlainNio2EchoServer {
public void serve(int port) throws IOException {
System.out.println("Listening for connections on port " + port);
final AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel
.open();
InetSocketAddress address = new InetSocketAddress(port);
serverChannel.bind(address);
final CountDownLatch latch = new CountDownLatch(1);
serverChannel.accept(null,
new CompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public void completed(
final AsynchronousSocketChannel channel,
Object attachment) {
serverChannel.accept(null, this);
ByteBuffer buffer = ByteBuffer.allocate(100);
channel.read(buffer, buffer, new EchoCompletionHandler(
channel));
} @Override
public void failed(Throwable throwable, Object attachment) {
try {
serverChannel.close();
} catch (IOException e) {
// ingnore on close
} finally {
latch.countDown();
}
}
});
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} private final class EchoCompletionHandler implements
CompletionHandler<Integer, ByteBuffer> {
private final AsynchronousSocketChannel channel; EchoCompletionHandler(AsynchronousSocketChannel channel) {
this.channel = channel;
} @Override
public void completed(Integer result, ByteBuffer buffer) {
buffer.flip();
channel.write(buffer, buffer,
new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer buffer) {
if (buffer.hasRemaining()) {
channel.write(buffer, buffer, this);
} else {
buffer.compact();
channel.read(buffer, buffer,
EchoCompletionHandler.this);
}
} @Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
channel.close();
} catch (IOException e) {
// ingnore on close
}
}
});
} @Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
channel.close();
} catch (IOException e) {
// ingnore on close
}
}
}
}

At first glance, it may look like more code than what you had when using the previous NIO

implementation. But notice that NIO.2 handles threading and the creation of the so-called

event loop for you. This approach simplifies the code needed to build a multithreaded NIO

application, even though it may not seem to be the case in this example. As the complexity of

the application increases, the gains become more evident because you’ll be producing cleaner

code.

Nio学习4——EchoServer在IO,NIO,NIO.2中的实现的更多相关文章

  1. JAVA NIO学习一:NIO简介、NIO&IO的主要区别

    在前面学习了IO之后,今天我们开始进入NIO学习环节,首先我们会NIO做一个简单的介绍,让大家认识NIO,然后会和IO进行一个对比认识进行区分.好了,下面我们就开始学习: 一.NIO简介 1.概述 从 ...

  2. Java:NIO 学习笔记-2

    Java:NIO 学习笔记-2 上一篇 NIO 学习笔记-1 看了 尚硅谷 的相应教程,此处又对比看了 黑马程序员 的课程 JAVA通信架构I/O模式,做了相应的笔记 前言 在 Java 的软件设计开 ...

  3. Java NIO 学习笔记(七)----NIO/IO 的对比和总结

    目录: Java NIO 学习笔记(一)----概述,Channel/Buffer Java NIO 学习笔记(二)----聚集和分散,通道到通道 Java NIO 学习笔记(三)----Select ...

  4. Java NIO学习系列四:NIO和IO对比

    前面的一些文章中我总结了一些Java IO和NIO相关的主要知识点,也是管中窥豹,IO类库已经功能很强大了,但是Java 为什么又要引入NIO,这是我一直不是很清楚的?前面也只是简单提及了一下:因为性 ...

  5. Java NIO学习笔记九 NIO与IO对比

    Java NIO与IO Java nio 和io 到底有什么区别,以及什么时候使用nio和io,本文做一个比较. Java NIO和IO之间的主要区别 下表总结了Java NIO和IO之间的主要区别, ...

  6. Java IO学习笔记五:BIO到NIO

    作者:Grey 原文地址: Java IO学习笔记五:BIO到NIO 准备环境 准备一个CentOS7的Linux实例: 实例的IP: 192.168.205.138 我们这次实验的目的就是直观感受一 ...

  7. vivo面试学习1(io和nio)

    一.io流(一次从open到底层的操作) 输入和输出流 IO流 字节流 Reader.Writer 字符流 InputStream.OutputStream 字节流:可以处理所有bit为单位存储的文件 ...

  8. JAVA NIO学习笔记1 - 架构简介

    最近项目中遇到不少NIO相关知识,之前对这块接触得较少,算是我的一个盲区,打算花点时间学习,简单做一点个人学习总结. 简介 NIO(New IO)是JDK1.4以后推出的全新IO API,相比传统IO ...

  9. java8 学习系列--NIO学习笔记

    近期有点时间,决定学习下java8相关的内容: 当然了不止java8中新增的功能点,整个JDK都需要自己研究的,不过这是个漫长的过程吧,以自己的惰性来看: 不过开发中不是有时候讲究模块化开发么,那么我 ...

随机推荐

  1. arcgis jsapi 调用google地区服务

    做地理信息系统(GIS)项目,除了实现功能用户体验度要好之外,最重要的是地图渲染效果更要好.很多时候苦于数据的完整性和对于配图的审美观,程序猿们都很难配出好看的地图效果.基于上述一般直接调用googl ...

  2. Python学习入门基础教程(learning Python)--2.3.1 Python传参函数设计

    本节主要讨论设计传递多个参数子函数的设计方法. 在2.3节里我们讨论了如何自己设计一个带参数的子函数的设计方法,现在我们研究一下如何传递两个及以上参数的设计方法. 函数为何要带参数呢?其实原因很简单, ...

  3. cocos2d-x 3.1.1 学习笔记[2]Sprite 精灵

    Sprite应该是用到最多的一个类吧.无法想像一个游戏没有精灵将怎样进行愉快的玩耍. Sprite继承于Node 和 TextureProtocol. Sprite是一个2d的图像. Sprite能够 ...

  4. C该程序生成一个唯一的序列号

    在实际的软件开发项目,通常,它包括产生一唯一的序列号.在本文中,一个切实可行的方案,例如,它引入了一个唯一的序列号生成过程. 本文生成的序列号的样式为:MMDDHHMINSS_XXXXXX. 程序例如 ...

  5. android笔记6——intent的使用

    今天挑出一节专门来说一下使用intent和intentfilter进行通信. 场景:一个Activity启动还有一个Activity. 前面已经讲了Fragment的切换,Fragment顾名思义是基 ...

  6. sharepoint 2013 使用powershell更改站点集配额和锁定

    打开sharepoint powershell 2013,使用管理员方式打开 逐行输入下面命令: $Admin =  new-object Microsoft.SharePoint.Administr ...

  7. 配置jndi服务,javax.naming.NamingException的四种情况

    1.当jndi服务没有启动,或者jndi服务的属性没有设置正确,抛出如下异常: javax.naming.CommunicationException: Can't find SerialContex ...

  8. The practice program of C on point

    //字符反向排列 //vision 1.2 #include<stdio.h> void reverse_string( char *str ) { char *string;//第一个字 ...

  9. uva 11992 为矩阵更新查询段树

    http://uva.onlinejudge.org/index.php? option=com_onlinejudge&Itemid=8&page=show_problem& ...

  10. VMware vSphere 服务器虚拟化之十六 桌面虚拟化之VMware Horizon View

       VMware vSphere服务器虚拟化之十六 桌面虚拟化之VMware Horizon View  VMware Horizon View (原VMware View的升级版现在版本5.2)是 ...