Skip to content

Commit

Permalink
公众号:bugstack虫洞栈 | 初入JavaIO之门BIO、NIO、AIO实战练习
Browse files Browse the repository at this point in the history
  • Loading branch information
fuzhengwei committed Oct 6, 2019
1 parent a753e5c commit 2ac356d
Show file tree
Hide file tree
Showing 19 changed files with 386 additions and 101 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package org.itstack.demo.netty.aio;

import io.netty.channel.ChannelHandlerContext;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

/**
* 消息处理器
* 微信公众号:bugstack虫洞栈 | 专注原创技术专题案例,以最易学习编程的方式分享知识,让萌新、小白、大牛都能有所收获。目前已完成的专题有;Netty4.x从入门到实战、用Java实现JVM、基于JavaAgent的全链路监控等,其他更多专题还在排兵布阵中。
* 论坛:http://bugstack.cn
* Create by 付政委 on @2019
*/
public abstract class ChannelAdapter implements CompletionHandler<Integer, Object> {

private AsynchronousSocketChannel channel;
private Charset charset;

public ChannelAdapter(AsynchronousSocketChannel channel, Charset charset) {
this.channel = channel;
this.charset = charset;
if (channel.isOpen()) {
channelActive(new ChannelHandler(channel, charset));
}
}

@Override
public void completed(Integer result, Object attachment) {
try {
final ByteBuffer buffer = ByteBuffer.allocate(1024);
final long timeout = 60 * 60L;
channel.read(buffer, timeout, TimeUnit.SECONDS, null, new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
if (result == -1) {
try {
channelInactive(new ChannelHandler(channel, charset));
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
buffer.flip();
channelRead(new ChannelHandler(channel, charset), charset.decode(buffer));
buffer.clear();
channel.read(buffer, timeout, TimeUnit.SECONDS, null, this);
}

@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}


@Override
public void failed(Throwable exc, Object attachment) {
exc.getStackTrace();
}

public abstract void channelActive(ChannelHandler ctx);

public abstract void channelInactive(ChannelHandler ctx);

// 读取消息抽象类
public abstract void channelRead(ChannelHandler ctx, Object msg);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package org.itstack.demo.netty.aio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
* 微信公众号:bugstack虫洞栈 | 专注原创技术专题案例,以最易学习编程的方式分享知识,让萌新、小白、大牛都能有所收获。目前已完成的专题有;Netty4.x从入门到实战、用Java实现JVM、基于JavaAgent的全链路监控等,其他更多专题还在排兵布阵中。
* 论坛:http://bugstack.cn
* Create by 付政委 on @2019
*/
public class ChannelHandler {

private AsynchronousSocketChannel channel;
private Charset charset;

public ChannelHandler(AsynchronousSocketChannel channel, Charset charset) {
this.channel = channel;
this.charset = charset;
}

public void writeAndFlush(Object msg) {
byte[] bytes = msg.toString().getBytes(charset);
ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
writeBuffer.put(bytes);
writeBuffer.flip();
channel.write(writeBuffer);
}

public AsynchronousSocketChannel channel() {
return channel;
}

public void setChannel(AsynchronousSocketChannel channel) {
this.channel = channel;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package org.itstack.demo.netty.aio;

import org.itstack.demo.netty.aio.server.AioServer;

import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
* 微信公众号:bugstack虫洞栈 | 专注原创技术专题案例,以最易学习编程的方式分享知识,让萌新、小白、大牛都能有所收获。目前已完成的专题有;Netty4.x从入门到实战、用Java实现JVM、基于JavaAgent的全链路监控等,其他更多专题还在排兵布阵中。
* 论坛:http://bugstack.cn
* Create by 付政委 on @2019
*/
public abstract class ChannelInitializer implements CompletionHandler<AsynchronousSocketChannel, AioServer> {

@Override
public void completed(AsynchronousSocketChannel channel, AioServer attachment) {
try {
initChannel(channel);
} catch (Exception e) {
e.printStackTrace();
} finally {
attachment.serverSocketChannel().accept(attachment, this);// 再此接收客户端连接
}
}

@Override
public void failed(Throwable exc, AioServer attachment) {
exc.getStackTrace();
}

protected abstract void initChannel(AsynchronousSocketChannel channel) throws Exception;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package org.itstack.demo.netty.aio.client;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.util.concurrent.Future;

/**
* 微信公众号:bugstack虫洞栈 | 专注原创技术专题案例,以最易学习编程的方式分享知识,让萌新、小白、大牛都能有所收获。目前已完成的专题有;Netty4.x从入门到实战、用Java实现JVM、基于JavaAgent的全链路监控等,其他更多专题还在排兵布阵中。
* 论坛:http://bugstack.cn
* Create by 付政委 on @2019
*/
public class AioClient {

public static void main(String[] args) throws Exception {
AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
Future<Void> future = socketChannel.connect(new InetSocketAddress("192.168.1.116", 7397));
System.out.println("itstack-demo-netty aio client start done. {关注公众号:bugstack虫洞栈 | 欢迎关注&获取源码}");
future.get();
socketChannel.read(ByteBuffer.allocate(1024), null, new AioClientHandler(socketChannel, Charset.forName("GBK")));
Thread.sleep(100000);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package org.itstack.demo.netty.aio.client;

import org.itstack.demo.netty.aio.ChannelAdapter;
import org.itstack.demo.netty.aio.ChannelHandler;

import java.io.IOException;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.util.Date;

/**
* 微信公众号:bugstack虫洞栈 | 专注原创技术专题案例,以最易学习编程的方式分享知识,让萌新、小白、大牛都能有所收获。目前已完成的专题有;Netty4.x从入门到实战、用Java实现JVM、基于JavaAgent的全链路监控等,其他更多专题还在排兵布阵中。
* 论坛:http://bugstack.cn
* Create by 付政委 on @2019
*/
public class AioClientHandler extends ChannelAdapter {

public AioClientHandler(AsynchronousSocketChannel channel, Charset charset) {
super(channel, charset);
}

@Override
public void channelActive(ChannelHandler ctx) {
try {
System.out.println("微信公众号:bugstack虫洞栈 | 链接报告信息:" + ctx.channel().getRemoteAddress());
//通知客户端链接建立成功
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public void channelInactive(ChannelHandler ctx) {
}

@Override
public void channelRead(ChannelHandler ctx, Object msg) {
System.out.println("微信公众号:bugstack虫洞栈 | 服务端收到:" + new Date() + " " + msg + "\r\n");
ctx.writeAndFlush("客户端信息处理Success!\r\n");
}

}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,34 +1,41 @@
package org.itstack.demo.netty.aio.server;

import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;

/**
* 微信公众号:bugstack虫洞栈 | 专注原创技术专题案例,以最易学习编程的方式分享知识,让萌新、小白、大牛都能有所收获。目前已完成的专题有;Netty4.x从入门到实战、用Java实现JVM、基于JavaAgent的全链路监控等,其他更多专题还在排兵布阵中。
* 论坛:http://bugstack.cn
* Create by 付政委 on @2019
*/
public class AioServer {
public class AioServer extends Thread {

AsynchronousServerSocketChannel asynchronousServerSocketChannel;
CountDownLatch latch;
private AsynchronousServerSocketChannel serverSocketChannel;

public static void main(String[] args) {
new AioServer().bind(7397);
}

private void bind(int port) {
@Override
public void run() {
try {
asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
asynchronousServerSocketChannel.bind(new InetSocketAddress(port));

latch = new CountDownLatch(1);
asynchronousServerSocketChannel.accept(this, new AcceptCompletionHandler());
serverSocketChannel = AsynchronousServerSocketChannel.open(AsynchronousChannelGroup.withCachedThreadPool(Executors.newCachedThreadPool(), 10));
serverSocketChannel.bind(new InetSocketAddress(7397));
System.out.println("itstack-demo-netty aio server start done. {关注公众号:bugstack虫洞栈 | 欢迎关注&获取源码}");
// 等待
CountDownLatch latch = new CountDownLatch(1);
serverSocketChannel.accept(this, new AioServerChannelInitializer());
latch.await();
} catch (Exception e) {
e.printStackTrace();
}
}

public AsynchronousServerSocketChannel serverSocketChannel() {
return serverSocketChannel;
}

public static void main(String[] args) {
new AioServer().start();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package org.itstack.demo.netty.aio.server;

import org.itstack.demo.netty.aio.ChannelInitializer;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

/**
* 微信公众号:bugstack虫洞栈 | 专注原创技术专题案例,以最易学习编程的方式分享知识,让萌新、小白、大牛都能有所收获。目前已完成的专题有;Netty4.x从入门到实战、用Java实现JVM、基于JavaAgent的全链路监控等,其他更多专题还在排兵布阵中。
* 论坛:http://bugstack.cn
* Create by 付政委 on @2019
*/
public class AioServerChannelInitializer extends ChannelInitializer {

@Override
protected void initChannel(AsynchronousSocketChannel channel) throws Exception {
channel.read(ByteBuffer.allocate(1024), 10, TimeUnit.SECONDS, null, new AioServerHandler(channel, Charset.forName("GBK")));
}

}
Loading

0 comments on commit 2ac356d

Please sign in to comment.