Netty简单案例
2019-03-26 本文已影响0人
上杉丶零
一本非常不错的小册:Netty 入门与实战:仿写微信 IM 即时通讯系统
Netty是一个异步事件驱动的网络应用框架,用于快速开发可维护的高性能服务器和客户端。
- 引入Maven依赖
<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.34.Final</version>
</dependency>
- 服务器端
package com.example.demo.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
public class NettyServer {
public static void main(String[] args) {
ServerBootstrap serverBootstrap = new ServerBootstrap();
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) {
nioSocketChannel.pipeline().addLast(new StringDecoder());
nioSocketChannel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String message) {
System.out.println(message);
}
});
}
}).bind(8000);
}
}
- 客户端
package com.example.demo.netty;
import java.util.Date;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
public class NettyClient {
public static void main(String[] args) throws InterruptedException {
Bootstrap bootstrap = new Bootstrap();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
Channel channel = bootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) {
nioSocketChannel.pipeline().addLast(new StringEncoder());
}
}).connect("127.0.0.1", 8000).sync().channel();
while (true) {
channel.writeAndFlush(new Date() + ": hello world!");
Thread.sleep(2000);
}
}
}
- 案例:自动绑定递增端口
package com.example.demo.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
public class Test {
public static void main(String[] args) {
ServerBootstrap serverBootstrap = new ServerBootstrap();
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) {
nioSocketChannel.pipeline().addLast(new StringDecoder());
nioSocketChannel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String message) {
System.out.println(message);
}
});
}
});
bind(serverBootstrap, 8000);
}
public static void bind(ServerBootstrap serverBootstrap, int port) {
serverBootstrap.bind(port).addListener(new GenericFutureListener<Future<? super Void>>() {
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
if (future.isSuccess()) {
System.out.println("端口[" + port + "]绑定成功!");
} else {
System.err.println("端口[" + port + "]绑定失败!");
bind(serverBootstrap, port + 1);
}
}
});
}
}
- 案例:失败重连
package com.example.demo.netty;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
public class Test {
public static final int MAX_RETRY = 5;
public static void main(String[] args) throws InterruptedException {
Bootstrap bootstrap = new Bootstrap();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
bootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {}
});
connect(bootstrap, "127.0.0.1", 8000, MAX_RETRY);
}
public static void connect(Bootstrap bootstrap, String host, int port, int retry) {
bootstrap.connect(host, port).addListener(future -> {
if (future.isSuccess()) {
System.out.println("连接成功");
} else if (retry == 0) {
System.err.println("重试次数已用完,放弃连接!");
} else {
int order = (MAX_RETRY - retry) + 1;
int delay = 1 << order;
System.err.println(new Date() + ": 连接失败,第" + order + "次重连……");
bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1), delay, TimeUnit.SECONDS);
}
});
}
}
- 案例:客户端与服务器端双向通信
- 服务器端
package com.example.demo.netty;
import java.nio.charset.Charset;
import java.util.Date;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
public class NettyServer {
public static void main(String[] args) {
ServerBootstrap serverBootstrap = new ServerBootstrap();
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) {
nioSocketChannel.pipeline().addLast(new FirstServerHandler());
}
}).bind(8000);
}
}
class FirstServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext channelHandlerContext, Object message) throws Exception {
ByteBuf byteBufIn = (ByteBuf) message;
System.out.println(new Date() + ": 服务端读到数据 -> " + byteBufIn.toString(Charset.forName("utf-8")));
// 回复数据到客户端
System.out.println(new Date() + ": 服务端写出数据");
ByteBuf byteBufOut = getByteBuf(channelHandlerContext);
channelHandlerContext.channel().writeAndFlush(byteBufOut);
}
private ByteBuf getByteBuf(ChannelHandlerContext channelHandlerContext) {
byte[] bs = "Hello World".getBytes(Charset.forName("utf-8"));
ByteBuf byteBuf = channelHandlerContext.alloc().buffer();
byteBuf.writeBytes(bs);
return byteBuf;
}
}
- 客户端
package com.example.demo.netty;
import java.nio.charset.Charset;
import java.util.Date;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
public class NettyClient {
public static void main(String[] args) throws InterruptedException {
Bootstrap bootstrap = new Bootstrap();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
bootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) {
nioSocketChannel.pipeline().addLast(new FirstClientHandler());
}
}).connect("127.0.0.1", 8000);
}
}
class FirstClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception {
System.out.println(new Date() + ": 客户端写出数据");
ByteBuf buffer = getByteBuf(channelHandlerContext);
channelHandlerContext.channel().writeAndFlush(buffer);
}
private ByteBuf getByteBuf(ChannelHandlerContext channelHandlerContext) {
ByteBuf byteBuf = channelHandlerContext.alloc().buffer();
byte[] bs = "Hello Leif".getBytes(Charset.forName("utf-8"));
byteBuf.writeBytes(bs);
return byteBuf;
}
@Override
public void channelRead(ChannelHandlerContext channelHandlerContext, Object message) throws Exception {
ByteBuf byteBuf = (ByteBuf) message;
System.out.println(new Date() + ": 客户端读到数据 -> " + byteBuf.toString(Charset.forName("utf-8")));
}
}
- ByteBuf API
package com.example.demo.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
public class ByteBufTest {
public static void main(String[] args) {
ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(9, 100);
print("allocate ByteBuf(9, 100)", byteBuf);
// write方法改变写指针,写完之后写指针未到capacity的时候,buffer仍然可写
byteBuf.writeBytes(new byte[] {1, 2, 3, 4});
print("writeBytes(1,2,3,4)", byteBuf);
// write方法改变写指针,写完之后写指针未到capacity的时候,buffer仍然可写, 写完int类型之后,写指针增加4
byteBuf.writeInt(12);
print("writeInt(12)", byteBuf);
// write方法改变写指针, 写完之后写指针等于capacity的时候,buffer不可写
byteBuf.writeBytes(new byte[] {5});
print("writeBytes(5)", byteBuf);
// write方法改变写指针,写的时候发现buffer不可写则开始扩容,扩容之后capacity随即改变
byteBuf.writeBytes(new byte[] {6});
print("writeBytes(6)", byteBuf);
// get方法不改变读写指针
System.out.println("getByte(3) return: " + byteBuf.getByte(3));
System.out.println("getShort(3) return: " + byteBuf.getShort(3));
System.out.println("getInt(3) return: " + byteBuf.getInt(3));
print("getByte()", byteBuf);
// set方法不改变读写指针
byteBuf.setByte(byteBuf.readableBytes() + 1, 0);
print("setByte()", byteBuf);
// read方法改变读指针
byte[] dst = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(dst);
print("readBytes(" + dst.length + ")", byteBuf);
}
private static void print(String action, ByteBuf buffer) {
System.out.println("after ==========" + action + "==========");
System.out.println("capacity(): " + buffer.capacity());
System.out.println("maxCapacity(): " + buffer.maxCapacity());
System.out.println("readerIndex(): " + buffer.readerIndex());
System.out.println("readableBytes(): " + buffer.readableBytes());
System.out.println("isReadable(): " + buffer.isReadable());
System.out.println("writerIndex(): " + buffer.writerIndex());
System.out.println("writableBytes(): " + buffer.writableBytes());
System.out.println("isWritable(): " + buffer.isWritable());
System.out.println("maxWritableBytes(): " + buffer.maxWritableBytes());
System.out.println();
}
}
after ==========allocate ByteBuf(9, 100)==========
capacity(): 9
maxCapacity(): 100
readerIndex(): 0
readableBytes(): 0
isReadable(): false
writerIndex(): 0
writableBytes(): 9
isWritable(): true
maxWritableBytes(): 100
after ==========writeBytes(1,2,3,4)==========
capacity(): 9
maxCapacity(): 100
readerIndex(): 0
readableBytes(): 4
isReadable(): true
writerIndex(): 4
writableBytes(): 5
isWritable(): true
maxWritableBytes(): 96
after ==========writeInt(12)==========
capacity(): 9
maxCapacity(): 100
readerIndex(): 0
readableBytes(): 8
isReadable(): true
writerIndex(): 8
writableBytes(): 1
isWritable(): true
maxWritableBytes(): 92
after ==========writeBytes(5)==========
capacity(): 9
maxCapacity(): 100
readerIndex(): 0
readableBytes(): 9
isReadable(): true
writerIndex(): 9
writableBytes(): 0
isWritable(): false
maxWritableBytes(): 91
after ==========writeBytes(6)==========
capacity(): 64
maxCapacity(): 100
readerIndex(): 0
readableBytes(): 10
isReadable(): true
writerIndex(): 10
writableBytes(): 54
isWritable(): true
maxWritableBytes(): 90
getByte(3) return: 4
getShort(3) return: 1024
getInt(3) return: 67108864
after ==========getByte()==========
capacity(): 64
maxCapacity(): 100
readerIndex(): 0
readableBytes(): 10
isReadable(): true
writerIndex(): 10
writableBytes(): 54
isWritable(): true
maxWritableBytes(): 90
after ==========setByte()==========
capacity(): 64
maxCapacity(): 100
readerIndex(): 0
readableBytes(): 10
isReadable(): true
writerIndex(): 10
writableBytes(): 54
isWritable(): true
maxWritableBytes(): 90
after ==========readBytes(10)==========
capacity(): 64
maxCapacity(): 100
readerIndex(): 10
readableBytes(): 0
isReadable(): false
writerIndex(): 10
writableBytes(): 54
isWritable(): true
maxWritableBytes(): 90