• Spring Boot + Netty + WebSocket 实现消息推送


    关于Netty

    Netty 是一个利用 Java 的高级网络的能力,隐藏其背后的复杂性而提供一个易于使用的 API 的客户端/服务器框架。

    2

    Maven依赖

    1. <dependencies>
    2. <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
    3. <dependency>
    4. <groupId>io.netty</groupId>
    5. <artifactId>netty-all</artifactId>
    6. <version>4.1.36.Final</version>
    7. </dependency>
    8. </dependencies>

    3

    SpringBootApplication

    启动器中需要new一个NettyServer,并显式调用启动netty。

    1. @SpringBootApplication
    2. public class SpringCloudStudyDemoApplication {
    3. public static void main(String[] args) {
    4. SpringApplication.run(SpringCloudStudyDemoApplication.class,args);
    5. try {
    6. new NettyServer(12345).start();
    7. System.out.println("https://blog.csdn.net/moshowgame");
    8. System.out.println("http://127.0.0.1:6688/netty-websocket/index");
    9. }catch(Exception e) {
    10. System.out.println("NettyServerError:"+e.getMessage());
    11. }
    12. }
    13. }

    4

    NettyServer

    启动的NettyServer,这里进行配置

    1. /**
    2. * NettyServer Netty服务器配置
    3. */
    4. public class NettyServer {
    5. private final int port;
    6. public NettyServer(int port) {
    7. this.port = port;
    8. }
    9. public void start() throws Exception {
    10. EventLoopGroup bossGroup = new NioEventLoopGroup();
    11. EventLoopGroup group = new NioEventLoopGroup();
    12. try {
    13. ServerBootstrap sb = new ServerBootstrap();
    14. sb.option(ChannelOption.SO_BACKLOG, 1024);
    15. sb.group(group, bossGroup) // 绑定线程池
    16. .channel(NioServerSocketChannel.class) // 指定使用的channel
    17. .localAddress(this.port)// 绑定监听端口
    18. .childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作
    19. @Override
    20. protected void initChannel(SocketChannel ch) throws Exception {
    21. System.out.println("收到新连接");
    22. //websocket协议本身是基于http协议的,所以这边也要使用http解编码器
    23. ch.pipeline().addLast(new HttpServerCodec());
    24. //以块的方式来写的处理器
    25. ch.pipeline().addLast(new ChunkedWriteHandler());
    26. ch.pipeline().addLast(new HttpObjectAggregator(8192));
    27. ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", null, true, 65536 * 10));
  • 相关阅读:
    基于现代深度学习的目标检测方法综述
    机器学习笔记之线性分类——线性判别分析(二)模型参数求解过程
    华为数据中心VS技术理论讲解
    Power Apps使用oData访问表数据并赋值前端
    Django配置多个数据库(两种方法)
    centos7安装mysql8.0.31
    线上应用部署了两台load为1四核服务器
    多路分支选择结构—switch语句
    OpenHarmony 社区运营报告(2023 年 10 月)
    LinuxFTP云盘-文件服务系统
  • 原文地址:https://blog.csdn.net/Q54665642ljf/article/details/126616926