• Springboot 搭建 WebSocket


    需求

    需求?开玩笑,干就完了!

    环境

    1. IntelliJ IDEA 2021.3.2
    2. springboot 2.3.3.RELEASE
    3. spring-boot-starter-websocket:2.7.0
    4. postman

    开搞

    前提:基于 gradle 搭建
    
    • 1
    • application.yml:
    server:
      port: 80 // 配置访问端口即可
    
    • 1
    • 2
    • build.gradle
    plugins {
        id 'org.springframework.boot' version '2.3.3.RELEASE'
        id 'java'
    }
    repositories {
         mavenCentral()
         // 配置阿里镜像,快的飞起
        maven { url 'https://plugins.gradle.org/m2/' }
        maven { url 'https://maven.aliyun.com/nexus/content/repositories/google' }
        maven { url 'https://maven.aliyun.com/nexus/content/groups/public/' }
        maven { url 'https://maven.aliyun.com/nexus/content/repositories/jcenter'}
    }
    
    dependencies {
        implementation 'org.springframework.boot:spring-boot-starter-websocket:2.7.0'
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • WebSocketApplication.java
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
    import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
    import org.springframework.context.annotation.ComponentScan;
    
    @ComponentScan(basePackages = "这里改成你Component所在的包")
    // 因为只做 WebSocket,这里过滤掉数据源注入
    @SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
    public class WebSocketApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(WebSocketApplication.class, args);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • WebSocketConfigurator.java
    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    
    import javax.websocket.server.ServerEndpointConfig;
    
    public class WebSocketConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
    
        private static volatile BeanFactory context;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            WebSocketConfigurator.context = applicationContext;
        }
    
        @Override
        public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
            return context.getBean(clazz);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • WebSocketConfig.java
    package com.zy.ws;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    
    @Configuration
    public class WebSocketConfig {
    
        /**
         * 这个 Bean 会自动注册使用注解 @ServerEndpoint 注解生命的 websocket
         * @return
         */
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    
        /**
         * 这个 Bean 让 Spring 能够捕获到请求
         * 这里可能说的不对
         * @return
         */
        @Bean
        public WebSocketConfigurator webSocketConfigurator() {
            return new WebSocketConfigurator();
        }
    
    }
    
    • 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
    • WebSocketServer.java
    import org.springframework.stereotype.Component;
    
    import javax.websocket.*;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.concurrent.CopyOnWriteArrayList;
    
    @Component
    // 监听指定连接
    @ServerEndpoint(value = "/ws/{username}", configurator = WebSocketConfigurator.class)
    public class WebSocketServer {
    
        // 实例化一个 websocket 的 session
        private Session session;
    
        @OnOpen
        public void onOpen(@PathParam("username") String username, Session session) {
            System.out.println("有连接进来了:" + username);
        }
    
        @OnMessage
        public void onMessage(String message) {
            System.out.println(String.format("接收到来自客户端的消息:【%s】", message));
        }
    
        @OnClose
        public void onClose(@PathParam("username") String username) {
            System.out.println("有连接关闭了:" + username);
        }
    
        @OnError
        public void onError(Throwable e) {
            System.out.println("出问题啦!!!");
        }
    
    }
    
    • 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

    后台部分写到这里启动程序基本没什么问题了,idea 直接启动

    • postman 连接
      在这里插入图片描述
    • 后端接收
      在这里插入图片描述
    • postman 发送消息
      在这里插入图片描述
    • 后端接收
      在这里插入图片描述

    完结晒花

  • 相关阅读:
    项目前的知识回顾
    软件测试界的三无简历,企业拿什么来招聘你,石沉大海的简历
    原子性,可见性,有序性详解及DCL单例模式两次校验的目的(拓展懒汉式,饿汉式)
    拼多多笔试
    零基础如何入门Web性能测试?
    2022.7.29好题选讲(计数专题)
    墨天轮沙龙 | 清华乔嘉林:Apache IoTDB,源于清华,建设开源生态之路
    中国20强游戏公司2022上半年年报分析:复合因素下业绩增长承压,海外新兴市场蕴含增长新趋势
    从入门到精通:Go 实现基于 Token 的登录流程深度指南
    大数据-玩转数据-Python几种数据采集
  • 原文地址:https://blog.csdn.net/wsgjcxy13/article/details/125563779