Nio学习4——EchoServer在IO,NIO,NIO.2中的实现
堵塞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中的实现的更多相关文章
- JAVA NIO学习一:NIO简介、NIO&IO的主要区别
在前面学习了IO之后,今天我们开始进入NIO学习环节,首先我们会NIO做一个简单的介绍,让大家认识NIO,然后会和IO进行一个对比认识进行区分.好了,下面我们就开始学习: 一.NIO简介 1.概述 从 ...
- Java:NIO 学习笔记-2
Java:NIO 学习笔记-2 上一篇 NIO 学习笔记-1 看了 尚硅谷 的相应教程,此处又对比看了 黑马程序员 的课程 JAVA通信架构I/O模式,做了相应的笔记 前言 在 Java 的软件设计开 ...
- Java NIO 学习笔记(七)----NIO/IO 的对比和总结
目录: Java NIO 学习笔记(一)----概述,Channel/Buffer Java NIO 学习笔记(二)----聚集和分散,通道到通道 Java NIO 学习笔记(三)----Select ...
- Java NIO学习系列四:NIO和IO对比
前面的一些文章中我总结了一些Java IO和NIO相关的主要知识点,也是管中窥豹,IO类库已经功能很强大了,但是Java 为什么又要引入NIO,这是我一直不是很清楚的?前面也只是简单提及了一下:因为性 ...
- Java NIO学习笔记九 NIO与IO对比
Java NIO与IO Java nio 和io 到底有什么区别,以及什么时候使用nio和io,本文做一个比较. Java NIO和IO之间的主要区别 下表总结了Java NIO和IO之间的主要区别, ...
- Java IO学习笔记五:BIO到NIO
作者:Grey 原文地址: Java IO学习笔记五:BIO到NIO 准备环境 准备一个CentOS7的Linux实例: 实例的IP: 192.168.205.138 我们这次实验的目的就是直观感受一 ...
- vivo面试学习1(io和nio)
一.io流(一次从open到底层的操作) 输入和输出流 IO流 字节流 Reader.Writer 字符流 InputStream.OutputStream 字节流:可以处理所有bit为单位存储的文件 ...
- JAVA NIO学习笔记1 - 架构简介
最近项目中遇到不少NIO相关知识,之前对这块接触得较少,算是我的一个盲区,打算花点时间学习,简单做一点个人学习总结. 简介 NIO(New IO)是JDK1.4以后推出的全新IO API,相比传统IO ...
- java8 学习系列--NIO学习笔记
近期有点时间,决定学习下java8相关的内容: 当然了不止java8中新增的功能点,整个JDK都需要自己研究的,不过这是个漫长的过程吧,以自己的惰性来看: 不过开发中不是有时候讲究模块化开发么,那么我 ...
随机推荐
- Flash Android ANE打包之基本流程
搭建环境这里就不详细说明了 一.Android本地库编写 1.从Flash Air SDK中提取需要的jar包 Android下需要的jar包在Flash Air SDK/lib/android目录下 ...
- WPF界面设计技巧(1)—不规则窗体图文指南
原文:WPF界面设计技巧(1)-不规则窗体图文指南 初到园子,奉上第一篇入门级教程,请勿见笑. 以往WinForm编程中,实现不规则窗体是有一定难度的,更难的是不规则窗体的边缘抗锯齿及局部透明处理.而 ...
- 压缩js参数保存解决方法
angular.js 中 找到 if (typeof fn === 'function') 在 if (fn.length) { console.warn("此函数没有注入注解,将导致编译 ...
- My Solution: Word Ladder
public class Solution { public int ladderLength(String start, String end, Set<String> dict) { ...
- [Unity3D]Unity3D游戏开发之飞机大战项目解说
大家好,我是秦元培,欢迎大家继续关注我的博客,我的博客地址是blog.csdn.net/qinyuanpei. 首先感谢大家对我博客的关注,今天我想和大家分享的是一个飞机大战的项目.这是一个比較综合的 ...
- Sqlite 扩展功能 GET_PHONEBOOK_INDEX
在联系人数据库设计中遇到了这个函数,晚上找了半天没找到答案. GET_PHONEBOOK_INDEX This function will produce a normalized upper cas ...
- Windows Phone开发(35):使用Express Blend绘图
原文:Windows Phone开发(35):使用Express Blend绘图 上一节中我们简单扯了一下绘图指令,然而那也不是最简单的绘图法,今天,我再向大家推荐一种更好的绘图方案--Express ...
- GNU名称解析
GNU它是GNU's NOT UNIX缩写G N U缩写,和GNU全名GNU's NOT UNIX 中间 GNU 也GNU's NOT UNIX缩写,它使用递归方式定义GNU.
- [Windwos Phone 8]多个按钮的共用事件
原文:[Windwos Phone 8]多个按钮的共用事件 前言 ------------------------------------------------------------------- ...
- BC 2015在百度之星程序设计大赛 - 预赛(1)(系列转换-二分法答案贪婪)
系列转换 Accepts: 816 Submissions: 3578 Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 ...