Netty4学习笔记-002
2014-04-07 22:51
555 查看
Blocking IO:
public
classPlainEchoServer {
publicvoidserve(intport)
throwsIOException {
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 {
BufferedReaderreader = newBufferedReader(
newInputStreamReader(clientSocket.getInputStream()));
PrintWriter writer= newPrintWriter(clientSocket
.getOutputStream(), true);
[b]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();
}
}
}
Non-blocking IO:
public
classPlainNioEchoServer {
publicvoidserve(intport)
throwsIOException {
System.out.println("Listening for connections on port "+ port);
ServerSocketChannel serverChannel;
Selector selector;
serverChannel = ServerSocketChannel.open();
ServerSocket ss = serverChannel.socket();
InetSocketAddress address = newInetSocketAddress(port);
ss.bind(address);
serverChannel.configureBlocking(false);
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) {
}
}
}
}
}
}
使用Java7以后才有的NIO2
public
classPlainNio2EchoServer {
publicvoidserve(intport)
throwsIOException {
System.out.println("Listening for connections on port "+ port);
final AsynchronousServerSocketChannelserverChannel = AsynchronousServerSocketChannel.open();
InetSocketAddress address = newInetSocketAddress(port);
serverChannel.bind(address);
final CountDownLatch
latch = new CountDownLatch(1);
serverChannel.accept(null,
newCompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public
void completed(final AsynchronousSocketChannel channel, Objectattachment) {
serverChannel.accept(null,
this);
ByteBuffer buffer = ByteBuffer.allocate(100);
channel.read(buffer, buffer, newEchoCompletionHandler(channel));
}
@Override
public
void failed(Throwable throwable, Objectattachment) {
try {
serverChannel.close();
} catch (IOException e) {
// ingnore on close
} finally {
latch.countDown();
}
}
});
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
privatefinalclassEchoCompletionHandler
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,
newCompletionHandler<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();
} [b]catch (IOException e) {
// ingnore on close
}
}
}
}
public
classPlainEchoServer {
publicvoidserve(intport)
throwsIOException {
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 {
BufferedReaderreader = newBufferedReader(
newInputStreamReader(clientSocket.getInputStream()));
PrintWriter writer= newPrintWriter(clientSocket
.getOutputStream(), true);
[b]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();
}
}
}
Non-blocking IO:
public
classPlainNioEchoServer {
publicvoidserve(intport)
throwsIOException {
System.out.println("Listening for connections on port "+ port);
ServerSocketChannel serverChannel;
Selector selector;
serverChannel = ServerSocketChannel.open();
ServerSocket ss = serverChannel.socket();
InetSocketAddress address = newInetSocketAddress(port);
ss.bind(address);
serverChannel.configureBlocking(false);
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) {
}
}
}
}
}
}
使用Java7以后才有的NIO2
public
classPlainNio2EchoServer {
publicvoidserve(intport)
throwsIOException {
System.out.println("Listening for connections on port "+ port);
final AsynchronousServerSocketChannelserverChannel = AsynchronousServerSocketChannel.open();
InetSocketAddress address = newInetSocketAddress(port);
serverChannel.bind(address);
final CountDownLatch
latch = new CountDownLatch(1);
serverChannel.accept(null,
newCompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public
void completed(final AsynchronousSocketChannel channel, Objectattachment) {
serverChannel.accept(null,
this);
ByteBuffer buffer = ByteBuffer.allocate(100);
channel.read(buffer, buffer, newEchoCompletionHandler(channel));
}
@Override
public
void failed(Throwable throwable, Objectattachment) {
try {
serverChannel.close();
} catch (IOException e) {
// ingnore on close
} finally {
latch.countDown();
}
}
});
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
privatefinalclassEchoCompletionHandler
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,
newCompletionHandler<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();
} [b]catch (IOException e) {
// ingnore on close
}
}
}
}
相关文章推荐
- Netty5入门学习笔记002-TCP粘包/拆包问题的解决之道(上)
- Perl学习笔记(002)
- Python学习笔记(基础篇)_002_类型转换
- MeVisLab学习笔记_002
- 关于直播学习笔记-002-Red5 & Sewise Player & Wirecast
- Excel学习笔记002-002:工作表内及工作表间、工作簿间单元格数据的复制、剪切、粘贴;如何进行成绩排序。
- Netty4学习笔记-- Bootstrap
- Hadoop学习笔记-002-CentOS_6.5_64_克隆系统后更改IP及主机名
- ThinkingInJava 学习笔记 002
- 【js学习笔记-002】--词法结构.Unicode转义序列
- 郝斌视频学习笔记002
- PHP学习笔记002——php5.2.6有关fetch_assoc()的bug
- Netty4学习笔记(5)-- NioEventLoopGroup继承层次结构
- 学习笔记002之学习资料
- ABAP学习笔记-基本的数据操作-002
- AngularJS学习笔记--002--Angular JS路由插件ui.router源码解析
- Excel学习笔记002-004:如何合并工作表或工作簿?
- Netty4学习笔记-- NioEventLoopGroup NioEventLoop
- python的学习笔记/002-2(2018-5-19)
- extjs学习笔记-----消息框002