溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在Spring Boot中利用netty實現(xiàn)客戶端服務(wù)端交互

發(fā)布時間:2021-06-02 16:40:23 來源:億速云 閱讀:1147 作者:Leah 欄目:編程語言

這篇文章給大家介紹怎么在Spring Boot中利用netty實現(xiàn)客戶端服務(wù)端交互,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

首先,當然是在SpringBoot項目里添加netty的依賴了,注意不要用netty5的依賴,因為已經(jīng)廢棄了

<!--netty-->
<dependency>
 <groupId>io.netty</groupId>
 <artifactId>netty-all</artifactId>
 <version>4.1.32.Final</version>
</dependency>

將端口和IP寫入application.yml文件里,我這里是我云服務(wù)器的內(nèi)網(wǎng)IP,如果是本機測試,用127.0.0.1就ok

netty:
 port: 7000
 url: 172.16.0.7

在這之后,開始寫netty的服務(wù)器,這里服務(wù)端的邏輯就是將客戶端發(fā)來的信息返回回去

因為采用依賴注入的方法實例化netty,所以加上@Component注釋

package com.safelocate.app.nettyServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Component
public class NettyServer {
 //logger
 private static final Logger logger = Logger.getLogger(NettyServer.class);
 public void start(InetSocketAddress address){
 EventLoopGroup bossGroup = new NioEventLoopGroup(1);
 EventLoopGroup workerGroup = new NioEventLoopGroup();
 try {
  ServerBootstrap bootstrap = new ServerBootstrap()
   .group(bossGroup,workerGroup)
   .channel(NioServerSocketChannel.class)
   .localAddress(address)
   .childHandler(new ServerChannelInitializer())
   .option(ChannelOption.SO_BACKLOG, 128)
   .childOption(ChannelOption.SO_KEEPALIVE, true);
  // 綁定端口,開始接收進來的連接
  ChannelFuture future = bootstrap.bind(address).sync();
  logger.info("Server start listen at " + address.getPort());
  future.channel().closeFuture().sync();
 } catch (Exception e) {
  e.printStackTrace();
  bossGroup.shutdownGracefully();
  workerGroup.shutdownGracefully();
 }
 }

}

當然,這里的ServerChannelInitializer是我自己定義的類,這個類是繼承ChannelInitializer<SocketChannel>的,里面設(shè)置出站和入站的編碼器和解碼器

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());
 }
}

最好注意被別decoder和encoder寫成了一樣的,不然會出問題(我之前就是不小心都寫成了StringDecoder...)

在這之后就是設(shè)置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);
 //刷新緩存區(qū)
 ctx.flush();
 }

 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
 cause.printStackTrace();
 ctx.close();
 }
}

準備工作到這里,現(xiàn)在要做到就是去啟動這個程序

將AppApplication實現(xiàn)CommandLineRunner這個接口,這個接口可以用來再啟動SpringBoot時同時啟動其他功能,比如配置,數(shù)據(jù)庫連接等等

然后重寫run方法,在run方法里啟動netty服務(wù)器,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);
 }
}

ok,到這里服務(wù)端已經(jīng)寫完,本地我也已經(jīng)測試完,現(xiàn)在需要打包部署服務(wù)器,當然這個程序只為練手...

控制臺輸入mvn clean package -D skipTests 然后將jar包上傳服務(wù)器,在這之后,需要在騰訊云/阿里云那邊配置好安全組,將之前yml文件里設(shè)定的端口的入站

規(guī)則設(shè)置好,不然訪問會被拒絕

之后java -jar命令運行,如果需保持后臺一直運行 就用nohup命令,可以看到程序已經(jīng)跑起來了,等待客戶端連接交互

怎么在Spring Boot中利用netty實現(xiàn)客戶端服務(wù)端交互

之后就是寫客戶端了,客戶端其實是依葫蘆畫瓢,跟上面類似

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();
 }

}

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());
 }
}

主函數(shù)所在類,即客戶端

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", "服務(wù)器的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();
 }
 }

}

啟動客戶端,這里就是簡單發(fā)送一條"hhhh",可以看到客戶端已經(jīng)收到服務(wù)器發(fā)來的信息


 怎么在Spring Boot中利用netty實現(xiàn)客戶端服務(wù)端交互

然后再看服務(wù)端,也有相應(yīng)的信息打印

怎么在Spring Boot中利用netty實現(xiàn)客戶端服務(wù)端交互

關(guān)于怎么在Spring Boot中利用netty實現(xiàn)客戶端服務(wù)端交互就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI