Java搭建簡(jiǎn)單Netty開(kāi)發(fā)環(huán)境入門(mén)教程
下面就是準(zhǔn)備N(xiāo)etty的jar包了,如果你會(huì)maven的話自然是使用maven最為方便了。只需要在pom文件中導(dǎo)入以下幾行
<!-- https://mvnrepository.com/artifact/io.netty/netty-all --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.16.Final</version> </dependency>
當(dāng)然啦,不會(huì)maven的也不用愁,可以在官網(wǎng)直接下載jar包,點(diǎn)擊跳轉(zhuǎn)。并在編輯器中將下載的jar包引入你的lib中,就可以愉快的開(kāi)始Netty開(kāi)發(fā)了
下面貼一個(gè)簡(jiǎn)單的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 { //將客戶(hù)端傳入的消息轉(zhuǎn)換為Netty的ByteBuf類(lèi)型 ByteBuf in = (ByteBuf) msg; // 在控制臺(tái)打印傳入的消息 System.out.println( "Server received: " + in.toString(CharsetUtil.UTF_8) ); //將接收到的消息寫(xiě)給發(fā)送者,而不沖刷出站消息 ctx.write(in); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { // 將未處決消息沖刷到遠(yuǎn)程節(jié)點(diǎn), 并且關(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)) // 添加一個(gè)EchoServerHandler到Channle的ChannelPipeline .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { //EchoServerHandler被標(biāo)注為@shareable,所以我們可以總是使用同樣的案例 socketChannel.pipeline().addLast(serverHandler); } }); try { // 異步地綁定服務(wù)器;調(diào)用sync方法阻塞等待直到綁定完成 ChannelFuture f = b.bind().sync(); // 獲取Channel的CloseFuture,并且阻塞當(dāng)前線程直到它完成 f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { // 優(yōu)雅的關(guān)閉EventLoopGroup,釋放所有的資源 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
二、 客戶(hù)端代碼
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 { //當(dāng)被通知Channel是活躍的時(shí)候,發(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(); } }
先后運(yùn)行EchoServer.java和EchoClient.java.如果控制臺(tái)分別打印了
Server received: Netty rocks!
和
Client received: Netty rocks!
那么恭喜你,你已經(jīng)可以開(kāi)始netty的開(kāi)發(fā)了。
點(diǎn)擊查看Netty結(jié)合Protobuf編解碼
到此這篇關(guān)于Java搭建簡(jiǎn)單Netty開(kāi)發(fā)環(huán)境入門(mén)教程的文章就介紹到這了,更多相關(guān)Java搭建Netty環(huán)境內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java基于Netty實(shí)現(xiàn)Http server的實(shí)戰(zhàn)
- Java基于websocket協(xié)議與netty實(shí)時(shí)視頻彈幕交互實(shí)現(xiàn)
- Java游戲服務(wù)器系列之Netty相關(guān)知識(shí)總結(jié)
- Java實(shí)戰(zhàn)之用springboot+netty實(shí)現(xiàn)簡(jiǎn)單的一對(duì)一聊天
- Java設(shè)計(jì)模式之責(zé)任鏈模式的概念、實(shí)現(xiàn)以及netty中的責(zé)任鏈模式
- 基于Java在netty中實(shí)現(xiàn)線程和CPU綁定
相關(guān)文章
Java對(duì)List進(jìn)行排序的方法總結(jié)
在Java中,對(duì)List進(jìn)行排序是一項(xiàng)常見(jiàn)的任務(wù),Java提供了多種方法來(lái)對(duì)List中的元素進(jìn)行排序,本文將詳細(xì)介紹如何使用Java來(lái)實(shí)現(xiàn)List的排序操作,涵蓋了常用的排序方法和技巧,需要的朋友可以參考下2024-07-07SpringCloud Alibaba項(xiàng)目實(shí)戰(zhàn)之nacos-server服務(wù)搭建過(guò)程
Nacos 是阿里巴巴推出來(lái)的一個(gè)新開(kāi)源項(xiàng)目,這是一個(gè)更易于構(gòu)建云原生應(yīng)用的動(dòng)態(tài)服務(wù)發(fā)現(xiàn)、配置管理和服務(wù)管理平臺(tái)。本章節(jié)重點(diǎn)給大家介紹SpringCloud Alibaba項(xiàng)目實(shí)戰(zhàn)之nacos-server服務(wù)搭建過(guò)程,感興趣的朋友一起看看吧2021-06-06詳解基于Spring Cloud幾行配置完成單點(diǎn)登錄開(kāi)發(fā)
這篇文章主要介紹了詳解基于Spring Cloud幾行配置完成單點(diǎn)登錄開(kāi)發(fā),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-02-02使用@RequestBody 接收復(fù)雜實(shí)體類(lèi)集合
這篇文章主要介紹了使用@RequestBody 接收復(fù)雜實(shí)體類(lèi)集合方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10詳解java中String、StringBuilder、StringBuffer的區(qū)別
這篇文章主要介紹了java中String、StringBuilder、StringBuffer的區(qū)別,文中講解的很清晰,有對(duì)于這方面不太懂的同學(xué)可以研究下2021-02-02java讀取cvs文件并導(dǎo)入數(shù)據(jù)庫(kù)
這篇文章主要為大家詳細(xì)介紹了java讀取cvs文件并導(dǎo)入數(shù)據(jù)庫(kù),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-08-08