当前位置:   article > 正文

Spring boot 集成netty实现websocket通信

Spring boot 集成netty实现websocket通信

一、netty介绍

Netty 是一个基于NIO的客户、服务器端的编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户、服务端应用。Netty相当于简化和流线化了网络应用的编程开发过程,例如:基于TCP和UDP的socket服务开发。快速”和“简单”并不用产生维护性或性能上的问题。Netty 是一个吸收了多种协议(包括FTP、SMTP、HTTP等各种二进制文本协议)的实现经验,并经过相当精心设计的项目。最终,Netty 成功的找到了一种方式,在保证易于开发的同时还保证了其应用的性能,稳定性和伸缩性

二、工程搭建

实验目标:实现推送消息给指定的用户

pom.xml

 
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>springboot-demo</artifactId>
  7. <groupId>com.et</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>netty</artifactId>
  12. <properties>
  13. <maven.compiler.source>8</maven.compiler.source>
  14. <maven.compiler.target>8</maven.compiler.target>
  15. </properties>
  16. <dependencies>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-web</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-autoconfigure</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-test</artifactId>
  28. <scope>test</scope>
  29. </dependency>
  30. <dependency>
  31. <groupId>io.netty</groupId>
  32. <artifactId>netty-all</artifactId>
  33. <version>4.1.87.Final</version>
  34. </dependency>
  35. <dependency>
  36. <groupId>cn.hutool</groupId>
  37. <artifactId>hutool-all</artifactId>
  38. <version>5.6.1</version>
  39. </dependency>
  40. </dependencies>
  41. </project>

属性文件

 
 
  1. server:
  2. port: 8088

netty server

 
 
  1. package com.et.netty.server;
  2. import com.et.netty.config.ProjectInitializer;
  3. import io.netty.bootstrap.ServerBootstrap;
  4. import io.netty.channel.ChannelFuture;
  5. import io.netty.channel.EventLoopGroup;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.nio.NioServerSocketChannel;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.beans.factory.annotation.Value;
  12. import org.springframework.stereotype.Component;
  13. import javax.annotation.PostConstruct;
  14. import javax.annotation.PreDestroy;
  15. import java.net.InetSocketAddress;
  16. /**
  17. * @author dongliang7
  18. * @projectName websocket-parent
  19. * @ClassName NettyServer.java
  20. * @description: TODO
  21. * @createTime 2023年02月06日 16:41:00
  22. */
  23. @Component
  24. public class NettyServer {
  25. static final Logger log = LoggerFactory.getLogger(NettyServer.class);
  26. /**
  27. * 端口号
  28. */
  29. @Value("${webSocket.netty.port:8889}")
  30. int port;
  31. EventLoopGroup bossGroup;
  32. EventLoopGroup workGroup;
  33. @Autowired
  34. ProjectInitializer nettyInitializer;
  35. @PostConstruct
  36. public void start() throws InterruptedException {
  37. new Thread(() -> {
  38. bossGroup = new NioEventLoopGroup();
  39. workGroup = new NioEventLoopGroup();
  40. ServerBootstrap bootstrap = new ServerBootstrap();
  41. // bossGroup辅助客户端的tcp连接请求, workGroup负责与客户端之前的读写操作
  42. bootstrap.group(bossGroup, workGroup);
  43. // 设置NIO类型的channel
  44. bootstrap.channel(NioServerSocketChannel.class);
  45. // 设置监听端口
  46. bootstrap.localAddress(new InetSocketAddress(port));
  47. // 设置管道
  48. bootstrap.childHandler(nettyInitializer);
  49. // 配置完成,开始绑定server,通过调用sync同步方法阻塞直到绑定成功
  50. ChannelFuture channelFuture = null;
  51. try {
  52. channelFuture = bootstrap.bind().sync();
  53. log.info("Server started and listen on:{}", channelFuture.channel().localAddress());
  54. // 对关闭通道进行监听
  55. channelFuture.channel().closeFuture().sync();
  56. } catch (InterruptedException e) {
  57. e.printStackTrace();
  58. }
  59. }).start();
  60. }
  61. /**
  62. * 释放资源
  63. */
  64. @PreDestroy
  65. public void destroy() throws InterruptedException {
  66. if (bossGroup != null) {
  67. bossGroup.shutdownGracefully().sync();
  68. }
  69. if (workGroup != null) {
  70. workGroup.shutdownGracefully().sync();
  71. }
  72. }
  73. }

ProjectInitializer

初始化,设置websocket handler

 
 
  1. package com.et.netty.config;
  2. import com.et.netty.handler.WebSocketHandler;
  3. import io.netty.channel.ChannelInitializer;
  4. import io.netty.channel.ChannelPipeline;
  5. import io.netty.channel.socket.SocketChannel;
  6. import io.netty.handler.codec.http.HttpObjectAggregator;
  7. import io.netty.handler.codec.http.HttpServerCodec;
  8. import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
  9. import io.netty.handler.codec.serialization.ObjectEncoder;
  10. import io.netty.handler.stream.ChunkedWriteHandler;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.beans.factory.annotation.Value;
  13. import org.springframework.stereotype.Component;
  14. /**
  15. * @author dongliang7
  16. * @projectName websocket-parent
  17. * @ClassName ProjectInitializer.java
  18. * @description: 管道配置
  19. * @createTime 2023年02月06日 16:43:00
  20. */
  21. @Component
  22. public class ProjectInitializer extends ChannelInitializer<SocketChannel> {
  23. /**
  24. * webSocket协议名
  25. */
  26. static final String WEBSOCKET_PROTOCOL = "WebSocket";
  27. /**
  28. * webSocket路径
  29. */
  30. @Value("${webSocket.netty.path:/webSocket}")
  31. String webSocketPath;
  32. @Autowired
  33. WebSocketHandler webSocketHandler;
  34. @Override
  35. protected void initChannel(SocketChannel socketChannel) throws Exception {
  36. // 设置管道
  37. ChannelPipeline pipeline = socketChannel.pipeline();
  38. // 流水线管理通道中的处理程序(Handler),用来处理业务
  39. // webSocket协议本身是基于http协议的,所以这边也要使用http编解码器
  40. pipeline.addLast(new HttpServerCodec());
  41. pipeline.addLast(new ObjectEncoder());
  42. // 以块的方式来写的处理器
  43. pipeline.addLast(new ChunkedWriteHandler());
  44. pipeline.addLast(new HttpObjectAggregator(8192));
  45. pipeline.addLast(new WebSocketServerProtocolHandler(webSocketPath, WEBSOCKET_PROTOCOL, true, 65536 * 10));
  46. // 自定义的handler,处理业务逻辑
  47. pipeline.addLast(webSocketHandler);
  48. }
  49. }

WebSocketHandler

 
 
  1. package com.et.netty.handler;
  2. import cn.hutool.json.JSONObject;
  3. import cn.hutool.json.JSONUtil;
  4. import com.et.netty.config.NettyConfig;
  5. import com.et.netty.server.NettyServer;
  6. import io.netty.channel.ChannelHandler;
  7. import io.netty.channel.ChannelHandlerContext;
  8. import io.netty.channel.SimpleChannelInboundHandler;
  9. import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
  10. import io.netty.util.AttributeKey;
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13. import org.springframework.stereotype.Component;
  14. /**
  15. * @author dongliang7
  16. * @projectName websocket-parent
  17. * @ClassName WebSocketHandler.java
  18. * @description: TODO
  19. * @createTime 2023年02月06日 16:44:00
  20. */
  21. @Component
  22. @ChannelHandler.Sharable
  23. public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
  24. private static final Logger log = LoggerFactory.getLogger(NettyServer.class);
  25. /**
  26. * 一旦连接,第一个被执行
  27. */
  28. @Override
  29. public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
  30. log.info("有新的客户端链接:[{}]", ctx.channel().id().asLongText());
  31. // 添加到channelGroup 通道组
  32. NettyConfig.getChannelGroup().add(ctx.channel());
  33. }
  34. /**
  35. * 读取数据
  36. */
  37. @Override
  38. protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
  39. log.info("服务器收到消息:{}", msg.text());
  40. // 获取用户ID,关联channel
  41. JSONObject jsonObject = JSONUtil.parseObj(msg.text());
  42. String uid = jsonObject.getStr("uid");
  43. NettyConfig.getChannelMap().put(uid, ctx.channel());
  44. // 将用户ID作为自定义属性加入到channel中,方便随时channel中获取用户ID
  45. AttributeKey<String> key = AttributeKey.valueOf("userId");
  46. ctx.channel().attr(key).setIfAbsent(uid);
  47. // 回复消息
  48. ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器收到消息啦"));
  49. }
  50. @Override
  51. public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
  52. log.info("用户下线了:{}", ctx.channel().id().asLongText());
  53. // 删除通道
  54. NettyConfig.getChannelGroup().remove(ctx.channel());
  55. removeUserId(ctx);
  56. }
  57. @Override
  58. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  59. log.info("异常:{}", cause.getMessage());
  60. // 删除通道
  61. NettyConfig.getChannelGroup().remove(ctx.channel());
  62. removeUserId(ctx);
  63. ctx.close();
  64. }
  65. /**
  66. * 删除用户与channel的对应关系
  67. */
  68. private void removeUserId(ChannelHandlerContext ctx) {
  69. AttributeKey<String> key = AttributeKey.valueOf("userId");
  70. String userId = ctx.channel().attr(key).get();
  71. NettyConfig.getChannelMap().remove(userId);
  72. }
  73. }

NettyConfig

 
 
  1. package com.et.netty.config;
  2. import io.netty.channel.Channel;
  3. import io.netty.channel.group.ChannelGroup;
  4. import io.netty.channel.group.DefaultChannelGroup;
  5. import io.netty.util.concurrent.GlobalEventExecutor;
  6. import java.util.concurrent.ConcurrentHashMap;
  7. /**
  8. * @author dongliang7
  9. * @projectName websocket-parent
  10. * @ClassName NettyConfig.java
  11. * @description: 管理全局Channel以及用户对应的channel(推送消息)
  12. * @createTime 2023年02月06日 16:43:00
  13. */
  14. public class NettyConfig {
  15. /**
  16. * 定义全局单利channel组 管理所有channel
  17. */
  18. private static volatile ChannelGroup channelGroup = null;
  19. /**
  20. * 存放请求ID与channel的对应关系
  21. */
  22. private static volatile ConcurrentHashMap<String, Channel> channelMap = null;
  23. /**
  24. * 定义两把锁
  25. */
  26. private static final Object lock1 = new Object();
  27. private static final Object lock2 = new Object();
  28. public static ChannelGroup getChannelGroup() {
  29. if (null == channelGroup) {
  30. synchronized (lock1) {
  31. if (null == channelGroup) {
  32. channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
  33. }
  34. }
  35. }
  36. return channelGroup;
  37. }
  38. public static ConcurrentHashMap<String, Channel> getChannelMap() {
  39. if (null == channelMap) {
  40. synchronized (lock2) {
  41. if (null == channelMap) {
  42. channelMap = new ConcurrentHashMap<>();
  43. }
  44. }
  45. }
  46. return channelMap;
  47. }
  48. public static Channel getChannel(String userId) {
  49. if (null == channelMap) {
  50. return getChannelMap().get(userId);
  51. }
  52. return channelMap.get(userId);
  53. }
  54. }

controller

 
 
  1. package com.et.netty.controller;
  2. import com.et.netty.service.PushMsgService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. /**
  9. * @author dongliang7
  10. * @projectName
  11. * @ClassName TestController.java
  12. * @description: TODO
  13. * @createTime 2023年02月06日 17:48:00
  14. */
  15. @RestController
  16. @RequestMapping("/push")
  17. public class TestController {
  18. @Autowired
  19. PushMsgService pushMsgService;
  20. /**
  21. * 推送消息到具体客户端
  22. * @param uid
  23. */
  24. @GetMapping("/{uid}")
  25. public void pushOne(@PathVariable String uid) {
  26. pushMsgService.pushMsgToOne(uid, "hello-------------------------");
  27. }
  28. /**
  29. * 推送消息到所有客户端
  30. */
  31. @GetMapping("/pushAll")
  32. public void pushAll() {
  33. pushMsgService.pushMsgToAll("hello all-------------------------");
  34. }
  35. }

PushMsgService

  1. package com.et.netty.service;
  2. /**
  3. * @author dongliang7
  4. * @projectName websocket-parent
  5. * @ClassName PushMsgService.java
  6. * @description: 推送消息接口
  7. * @createTime 2023年02月06日 16:44:00
  8. */
  9. public interface PushMsgService {
  10. /**
  11. * 推送给指定用户
  12. */
  13. void pushMsgToOne(String userId, String msg);
  14. /**
  15. * 推送给所有用户
  16. */
  17. void pushMsgToAll(String msg);
  18. }

PushMsgServiceImpl

  1. package com.et.netty.service;
  2. import com.et.netty.config.NettyConfig;
  3. import io.netty.channel.Channel;
  4. import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
  5. import org.springframework.stereotype.Service;
  6. import java.util.Objects;
  7. /**
  8. * @author dongliang7
  9. * @projectName websocket-parent
  10. * @ClassName PushMsgServiceImpl.java
  11. * @description: 推送消息实现类
  12. * @createTime 2023年02月06日 16:45:00
  13. */
  14. @Service
  15. public class PushMsgServiceImpl implements PushMsgService {
  16. @Override
  17. public void pushMsgToOne(String userId, String msg) {
  18. Channel channel = NettyConfig.getChannel(userId);
  19. if (Objects.isNull(channel)) {
  20. throw new RuntimeException("未连接socket服务器");
  21. }
  22. channel.writeAndFlush(new TextWebSocketFrame(msg));
  23. }
  24. @Override
  25. public void pushMsgToAll(String msg) {
  26. NettyConfig.getChannelGroup().writeAndFlush(new TextWebSocketFrame(msg));
  27. }
  28. }

文章值贴出部分关键代码,具体的详情代码参加代码仓库的netty模块

代码仓库

  • https://github.com/Harries/springboot-demo

三、测试

启动springboot工程

2024-03-08 11:21:32.975  INFO 10348 --- [       Thread-2] com.et.netty.server.NettyServer          : Server started and listen on:/0:0:0:0:0:0:0:0:8889

postman创建websocket连接 ws://127.0.0.1:8889/webSocket,并发送消息{'uid':'sss'}给服务端95ed8191ebb1c8c9f021df580ed604bf.png打开浏览器,给用户sss推送消息 http://127.0.0.1:8088/push/sssbb8db40adbcff28d239bc1495dff7c36.png 

四、引用

  • https://www.cnblogs.com/dongl961230/p/17099057.html

  • http://www.liuhaihua.cn/archives/710299.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/218541
推荐阅读
相关标签
  

闽ICP备14008679号