Netty權威指南_札記03_Netty入門應用
阿新 • • 發佈:2018-11-20
文章目錄
Netty權威指南_札記03_Netty入門應用
0. 引入pom依賴
<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha1</version>
</dependency>
1. Netty服務端開發
1.1 Netty時間伺服器服務端 TimeServer
import com.superbeyone.netty.handler.ChildChannelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* @program: study_netty
* @description: Netty時間伺服器 服務端
* @author: Mr.superbeyone
* @create: 2018-11-09 09:52
**/
public class TimeServer {
public void bind(int port) {
//配置服務端的NIO執行緒組
NioEventLoopGroup boss = new NioEventLoopGroup();
NioEventLoopGroup work = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss, work)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new TimeServerHandler()); //新增handler
}
});
//繫結埠,同步等待成功
ChannelFuture future = bootstrap.bind(port).sync();
//等待服務端監聽埠關閉
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
//優雅退出,釋放執行緒池資源
boss.shutdownGracefully();
work.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("服務端異常:"+e.getMessage());
}
}
new TimeServer().bind(port);
}
}
1.2 Netty時間伺服器服務端 TimeServerHandler
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.util.Date;
/**
* @program: study_netty
* @description: Netty時間伺服器服務端
* @author: Mr.superbeyone
* @create: 2018-11-09 10:27
**/
public class TimeServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
String body = new String(bytes, "UTF-8");
System.out.println("The time server receive order:\t" + body);
String currentTime = "query time order".equalsIgnoreCase(body) ? new Date().toString() : "Bad Order";
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
cause.printStackTrace();
}
}
2. Netty客戶端開發
2.1 Netty時間伺服器客戶端 TimeClient
import com.superbeyone.netty.handler.TimeClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* @program: study_netty
* @description: Netty時間伺服器客戶端NettyClient
* @author: Mr.superbeyone
* @create: 2018-11-09 10:37
**/
public class TimeClient {
public void connect(int port, String host) throws Exception {
//配置客戶端NIO執行緒組
NioEventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new TimeClientHandler()); //新增handler
}
});
//發起非同步連線操作
ChannelFuture future = bootstrap.connect(host, port).sync();
//等待客戶端鏈路關閉
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
//優雅的退出,釋放Nio執行緒組
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
new TimeClient().connect(port, "127.0.0.1");
}
}
2.2 Netty時間伺服器客戶端 TimeClientHandler
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
* @program: study_netty
* @description: Netty時間伺服器客戶端 TimeClientHandler
* @author: Mr.superbeyone
* @create: 2018-11-09 11:20
**/
public class TimeClientHandler extends ChannelHandlerAdapter {
private final ByteBuf message;
public TimeClientHandler() {
byte[] bytes = "query time order".getBytes();
message = Unpooled.buffer(bytes.length);
message.writeBytes(bytes);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(message);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
String body = new String(bytes, "UTF-8");
System.out.println("現在時間是:" + body);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("異常:" + cause.getMessage());
//釋放資源
ctx.close();
}
}