netty-第一個demo
搭建環境
maven引入
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.12.Final</version>
</dependency>
服務端
Netty 服務器都需要以下兩部分
- 至少一個 ChannelHandler — 該組件實現了服務器對從客戶端接收的數據的處理,即它的業務邏輯。
- 引導 — 這是配置服務器的啓動代碼。至少,它會將服務器綁定到它要監聽連接請求的端口上
channelHandler
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
// 對於每個傳入的消息都要調用
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
System.out.println("server recevied:"+ in.toString(StandardCharsets.UTF_8));
ctx.write(in);
}
// 通知ChannelInboundHandler最後一次對channel-
//Read()的調用是當前批量讀取中的最後一條消息
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
// 在讀取操作期間,有異常拋出時會調用
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("讀取操作錯誤信息");
cause.printStackTrace(); //打印錯誤
ctx.close();//關閉channel
}
}
BootStrap
public class EchoServer {
private final int port;
public EchoServer(int port) {
this.port = port;
}
public static void main(String[] args) throws InterruptedException {
int port = Integer.parseInt("1234");
new EchoServer(port).start();
}
//綁定到服務器將在其上監聽並接受傳入連接請求的端口;
//配置 Channel ,以將有關的入站消息通知給 EchoServerHandler 實例
private void start() throws InterruptedException {
final EchoServerHandler serverHandler = new EchoServerHandler();
NioEventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); //創建bootstrap
b.group(group)
.channel(NioServerSocketChannel.class) //使用nio傳輸channel
.localAddress(port) // 綁定端口
.childHandler(new ChannelInitializer<SocketChannel>() {
// 添加一個EchoServer-
//Handler 到子Channel
//的 ChannelPipeline
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(serverHandler);
// EchoServerHandler被標註爲@Shareable,所以我們可以總是使用同樣的實例
}
});
// 異步地綁定服務器;調用 sync()方法阻塞等待直到綁定完成
ChannelFuture f = b.bind().sync();
// 獲取 Channel 的CloseFuture,並且阻塞當前線程直到它完成
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
group.shutdownGracefully().sync();
}
}
}
客戶端
EchoClientHandler
@Sharable
public class EchoClientHandler
extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!",
CharsetUtil.UTF_8));
}
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) {
System.out.println(
"Client received: " + in.toString(CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
BootStrap
public class EchoClient {
private final String host;
private final int port;
public EchoClient(String host, int port) {
this.host = host;
this.port = port;
}
public static void main(String[] args) throws InterruptedException {
final String host = "127.0.0.1";
final int port = Integer.parseInt("1234");
new EchoClient(host, port).start();
}
private void start() throws InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(host,port)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoClientHandler());
}
});
ChannelFuture future = b.connect().sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
group.shutdownGracefully().sync();
}
}
}
運行
- 先啓動服務端
- 再啓動客戶端
服務端結果
server recevied:Netty Socket!
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-NoEjY2Eb-1571234128207)(C:\Users\ronny\OneDrive\筆記\高併發\picture\1571232070255.png)]
參考文檔
[Netty 拆包粘包和服務啓動流程分析](https://segmentfault.com/a/1190000013039327)
netty實戰