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 搭建
  • application.yml:
server:
  port: 80 // 配置访问端口即可
  • 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'
}
  • 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);
    }

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

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

}
  • 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("出问题啦!!!");
    }

}

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

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

完结晒花

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rising_chain

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值