SpringBoot整合netty實現客戶端服務端互動
看了好幾天的netty實戰,慢慢摸索,雖然還沒有摸著很多門道,但今天還是把之前想加入到專案裡的
一些想法實現了,算是有點信心了吧(講真netty對初學者還真的不是很友好......)
首先,當然是在SpringBoot專案裡新增netty的依賴了,注意不要用netty5的依賴,因為已經廢棄了
<!--netty--> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.32.Final</version> </dependency>
將埠和IP寫入application.yml檔案裡,我這裡是我雲伺服器的內網IP,如果是本機測試,用127.0.0.1就ok
netty: port: 7000 url: 172.16.0.7
在這之後,開始寫netty的伺服器,這裡服務端的邏輯就是將客戶端發來的資訊返回回去
因為採用依賴注入的方法例項化netty,所以加上@Component註釋
1 package com.safelocate.app.nettyServer; 2 3 import io.netty.bootstrap.ServerBootstrap;Server.java4 import io.netty.channel.*; 5 import io.netty.channel.nio.NioEventLoopGroup; 6 import io.netty.channel.socket.nio.NioServerSocketChannel; 7 import org.apache.log4j.Logger; 8 import org.springframework.stereotype.Component; 9 10 import java.net.InetSocketAddress; 11 12 @Component 13 public classNettyServer { 14 //logger 15 private static final Logger logger = Logger.getLogger(NettyServer.class); 16 public void start(InetSocketAddress address){ 17 EventLoopGroup bossGroup = new NioEventLoopGroup(1); 18 EventLoopGroup workerGroup = new NioEventLoopGroup(); 19 try { 20 ServerBootstrap bootstrap = new ServerBootstrap() 21 .group(bossGroup,workerGroup) 22 .channel(NioServerSocketChannel.class) 23 .localAddress(address) 24 .childHandler(new ServerChannelInitializer()) 25 .option(ChannelOption.SO_BACKLOG, 128) 26 .childOption(ChannelOption.SO_KEEPALIVE, true); 27 // 繫結埠,開始接收進來的連線 28 ChannelFuture future = bootstrap.bind(address).sync(); 29 logger.info("Server start listen at " + address.getPort()); 30 future.channel().closeFuture().sync(); 31 } catch (Exception e) { 32 e.printStackTrace(); 33 bossGroup.shutdownGracefully(); 34 workerGroup.shutdownGracefully(); 35 } 36 } 37 38 }
當然,這裡的ServerChannelInitializer是我自己定義的類,這個類是繼承ChannelInitializer<SocketChannel>的,裡面設定出站和入站的編碼器和解碼器
package com.safelocate.app.nettyServer; import io.netty.channel.ChannelInitializer; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast("decoder",new StringDecoder(CharsetUtil.UTF_8)); channel.pipeline().addLast("encoder",new StringEncoder(CharsetUtil.UTF_8)); channel.pipeline().addLast(new ServerHandler()); } }ServerChannelinitializer.java
最好注意被把decoder和encoder寫成了一樣的,不然會出問題
在這之後就是設定ServerHandler來處理一些簡單的邏輯了
package com.safelocate.app.nettyServer; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.SimpleChannelInboundHandler; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; public class ServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { System.out.println("channelActive----->"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("server channelRead......"); System.out.println(ctx.channel().remoteAddress()+"----->Server :"+ msg.toString()); //將客戶端的資訊直接返回寫入ctx ctx.write("server say :"+msg); //重新整理快取區 ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }ServerHandler.java
準備工作到這裡,現在要做到就是去啟動這個程式
將AppApplication實現CommandLineRunner這個介面,這個介面可以用來再啟動SpringBoot時同時啟動其他功能,比如配置,資料庫連線等等
然後重寫run方法,在run方法裡啟動netty伺服器,Server類用@AutoWired直接例項化
package com.safelocate.app; import com.safelocate.app.nettyServer.NettyServer; import io.netty.channel.ChannelFuture; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.net.InetAddress; import java.net.InetSocketAddress; @SpringBootApplication public class AppApplication implements CommandLineRunner { @Value("${netty.port}") private int port; @Value("${netty.url}") private String url; @Autowired private NettyServer server; public static void main(String[] args) { SpringApplication.run(AppApplication.class, args); } @Override public void run(String... args) throws Exception { InetSocketAddress address = new InetSocketAddress(url,port); System.out.println("run .... . ... "+url); server.start(address); } }AppApplication.java
ok,到這裡服務端已經寫完,本地我也已經測試完,現在需要打包部署伺服器,當然這個程式只為練手...
控制檯輸入mvn clean package -D skipTests 然後將jar包上傳伺服器,在這之後,需要在騰訊雲/阿里雲那邊配置好安全組,將之前yml檔案裡設定的埠的入站
規則設定好,不然訪問會被拒絕
之後java -jar命令執行,如果需保持後臺一直執行 就用nohup命令,可以看到程式已經跑起來了,等待客戶端連線互動
之後就是寫客戶端了,客戶端其實是依葫蘆畫瓢,跟上面類似
Handler
package client; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class ClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { System.out.println("ClientHandler Active"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { System.out.println("--------"); System.out.println("ClientHandler read Message:"+msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }ClientHandler.java
ChannelInitializer
package client; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> { protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline p = channel.pipeline(); p.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8)); p.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); p.addLast(new ClientHandler()); } }ClientChannelInitializer
主函式所在類,即客戶端
package client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; public class Client { static final String HOST = System.getProperty("host", "伺服器的IP地址"); static final int PORT = Integer.parseInt(System.getProperty("port", "7000")); static final int SIZE = Integer.parseInt(System.getProperty("size", "256")); public static void main(String[] args) throws Exception { sendMessage("hhhh"); } public static void sendMessage(String content) throws InterruptedException{ // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new StringDecoder()); p.addLast("encoder", new StringEncoder()); p.addLast(new ClientHandler()); } }); ChannelFuture future = b.connect(HOST, PORT).sync(); future.channel().writeAndFlush(content); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } }Client.java
啟動客戶端,這裡就是簡單傳送一條"hhhh",可以看到客戶端已經收到伺服器發來的資訊
然後再看服務端,也有相應的資訊列印
推薦一個挺好的學netty的部落格,https://blog.csdn.net/linuu/article/details/51306480,搭配netty實戰這本書一起學習效果很好