Java搭建簡單Netty開發(fā)環(huán)境入門教程
下面就是準備Netty的jar包了,如果你會maven的話自然是使用maven最為方便了。只需要在pom文件中導入以下幾行
<!-- https://mvnrepository.com/artifact/io.netty/netty-all --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.16.Final</version> </dependency>
當然啦,不會maven的也不用愁,可以在官網(wǎng)直接下載jar包,點擊跳轉(zhuǎn)。并在編輯器中將下載的jar包引入你的lib中,就可以愉快的開始Netty開發(fā)了
下面貼一個簡單的netty案例
一、 服務(wù)端代碼
1. EchoServerHandler.java
import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; @Sharable public class EchoServerHandler extends ChannelInboundHandlerAdapter{ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { //將客戶端傳入的消息轉(zhuǎn)換為Netty的ByteBuf類型 ByteBuf in = (ByteBuf) msg; // 在控制臺打印傳入的消息 System.out.println( "Server received: " + in.toString(CharsetUtil.UTF_8) ); //將接收到的消息寫給發(fā)送者,而不沖刷出站消息 ctx.write(in); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { // 將未處決消息沖刷到遠程節(jié)點, 并且關(guān)閉該Channel ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } /** * 異常處理 * @param ctx * @param cause * @throws Exception */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { //打印異常棧跟蹤 cause.printStackTrace(); // 關(guān)閉該Channel ctx.close(); } }
2. EchoServer.java
import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import java.net.InetSocketAddress; public class EchoServer { private final static int port = 8080; public static void main(String[] args) { start(); } private static void start() { final EchoServerHandler serverHandler = new EchoServerHandler(); // 創(chuàng)建EventLoopGroup EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); // 創(chuàng)建EventLoopGroup ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) //指定所使用的NIO傳輸Channel .channel(NioServerSocketChannel.class) //使用指定的端口設(shè)置套接字地址 .localAddress(new InetSocketAddress(port)) // 添加一個EchoServerHandler到Channle的ChannelPipeline .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { //EchoServerHandler被標注為@shareable,所以我們可以總是使用同樣的案例 socketChannel.pipeline().addLast(serverHandler); } }); try { // 異步地綁定服務(wù)器;調(diào)用sync方法阻塞等待直到綁定完成 ChannelFuture f = b.bind().sync(); // 獲取Channel的CloseFuture,并且阻塞當前線程直到它完成 f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { // 優(yōu)雅的關(guān)閉EventLoopGroup,釋放所有的資源 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
二、 客戶端代碼
1. EchoClientHandler.java
import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.util.CharsetUtil; @Sharable public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { //當被通知Channel是活躍的時候,發(fā)送一條消息 ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8)); } @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception { System.out.println( "Client received: " + byteBuf.toString(CharsetUtil.UTF_8) ); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
2. EchoClient.java
import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; public class EchoClient { private final static String HOST = "localhost"; private final static int PORT = 8080; public static void start() { EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(HOST, PORT)) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new EchoClientHandler()); } }); try { ChannelFuture f = bootstrap.connect().sync(); f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); }finally { group.shutdownGracefully(); } } public static void main(String[] args) { start(); } }
先后運行EchoServer.java和EchoClient.java.如果控制臺分別打印了
Server received: Netty rocks!
和
Client received: Netty rocks!
那么恭喜你,你已經(jīng)可以開始netty的開發(fā)了。
到此這篇關(guān)于Java搭建簡單Netty開發(fā)環(huán)境入門教程的文章就介紹到這了,更多相關(guān)Java搭建Netty環(huán)境內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringCloud Alibaba項目實戰(zhàn)之nacos-server服務(wù)搭建過程
Nacos 是阿里巴巴推出來的一個新開源項目,這是一個更易于構(gòu)建云原生應(yīng)用的動態(tài)服務(wù)發(fā)現(xiàn)、配置管理和服務(wù)管理平臺。本章節(jié)重點給大家介紹SpringCloud Alibaba項目實戰(zhàn)之nacos-server服務(wù)搭建過程,感興趣的朋友一起看看吧2021-06-06詳解基于Spring Cloud幾行配置完成單點登錄開發(fā)
這篇文章主要介紹了詳解基于Spring Cloud幾行配置完成單點登錄開發(fā),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02詳解java中String、StringBuilder、StringBuffer的區(qū)別
這篇文章主要介紹了java中String、StringBuilder、StringBuffer的區(qū)別,文中講解的很清晰,有對于這方面不太懂的同學可以研究下2021-02-02