下面就是準備Netty的jar包了,如果你會maven的話自然是使用maven最為方便了。只需要在pom文件中導入以下幾行
1
2
3
4
5
6
|
<!-- 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的也不用愁,可以在官網直接下載jar包,點擊跳轉。并在編輯器中將下載的jar包引入你的lib中,就可以愉快的開始Netty開發了
下面貼一個簡單的netty案例
一、 服務端代碼
1. EchoServerHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
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 { //將客戶端傳入的消息轉換為Netty的ByteBuf類型 ByteBuf in = (ByteBuf) msg; // 在控制臺打印傳入的消息 System.out.println( "Server received: " + in.toString(CharsetUtil.UTF_8) ); //將接收到的消息寫給發送者,而不沖刷出站消息 ctx.write(in); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { // 將未處決消息沖刷到遠程節點, 并且關閉該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(); // 關閉該Channel ctx.close(); } } |
2. EchoServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
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(); // 創建EventLoopGroup EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); // 創建EventLoopGroup ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) //指定所使用的NIO傳輸Channel .channel(NioServerSocketChannel. class ) //使用指定的端口設置套接字地址 .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 { // 異步地綁定服務器;調用sync方法阻塞等待直到綁定完成 ChannelFuture f = b.bind().sync(); // 獲取Channel的CloseFuture,并且阻塞當前線程直到它完成 f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { // 優雅的關閉EventLoopGroup,釋放所有的資源 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } |
二、 客戶端代碼
1. EchoClientHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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是活躍的時候,發送一條消息 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
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!
那么恭喜你,你已經可以開始netty的開發了。
點擊查看Netty結合Protobuf編解碼
到此這篇關于Java搭建簡單Netty開發環境入門教程的文章就介紹到這了,更多相關Java搭建Netty環境內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_33227649/article/details/78317912