SpringBoot整合WebSocket

流程分析

Websocket客户端与Websocket服务器端

前端浏览器和后端服务器的连接通信

HTTP与Websocket对比

服务器端编码

1.引入pom依赖

XML 复制代码
<!--webSocket-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  1. 编写配置类
java 复制代码
@Configuration
public class WebSocketConfig
{

    @Bean
    public ServerEndpointExporter serverEndpointExporter()
    {
        return new ServerEndpointExporter();
    }
}

3.编写服务代码

java 复制代码
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * WebSocket服务器设置
 */
@ServerEndpoint(value = "/wsServer/{userId}")
@Component
public class WebSocketServer
{

    // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    public static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    public static ConcurrentHashMap<String, WebSocketServer> typeMap = new ConcurrentHashMap<>();
    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    // 接收userId
    private String userId = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId)
    {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId))
        {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else
        {
            webSocketMap.put(userId, this);
        }
        try
        {
            sendMessage("我是服务端,你连接成功了!");
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose()
    {
        if (webSocketMap.containsKey(userId))
        {
            webSocketMap.remove(userId);
        }
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session)
    {
        if (StringUtils.isNotBlank(message))
        {
            try
            {
                // 解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                String type = (String) jsonObject.get("type");
                if (typeMap.containsKey(type))
                {
                    typeMap.remove(type);
                    typeMap.put(type, this);
                } else
                {
                    typeMap.put(type, this);
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error)
    {
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException
    {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException
    {
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId))
        {
            webSocketMap.get(userId).sendMessage(message);
        }
    }

}

4.状态变更通知前端

java 复制代码
// 通过WebSocket通知前端人员下发状态变更
try
{
    // 通过map获取对应的session
    WebSocketServer.typeMap.get("userId").sendMessage(封装的消息体);
} catch (IOException e)
{
    throw new RuntimeException(e);
}
相关推荐
程序员岳焱6 小时前
Java 与 MySQL 性能优化:Java 实现百万数据分批次插入的最佳实践
后端·mysql·性能优化
麦兜*6 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
KK溜了溜了7 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
大只鹅7 小时前
解决 Spring Boot 对 Elasticsearch 字段没有小驼峰映射的问题
spring boot·后端·elasticsearch
ai小鬼头7 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github
天河归来7 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
IT_10247 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
bobz9658 小时前
动态规划
后端
stark张宇8 小时前
VMware 虚拟机装 Linux Centos 7.9 保姆级教程(附资源包)
linux·后端
武昌库里写JAVA8 小时前
Oracle如何使用序列 Oracle序列使用教程
java·开发语言·spring boot·学习·课程设计