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);
}
相关推荐
David爱编程1 小时前
深度解析:synchronized 性能演进史,从 JDK1.6 到 JDK17
java·后端
脑子慢且灵1 小时前
【JavaWeb】一个简单的Web浏览服务程序
java·前端·后端·servlet·tomcat·web·javaee
用户298698530141 小时前
如何在 C# 中用表格替换 Word 文档中的文本?
后端
上官浩仁2 小时前
springboot synchronized 本地锁入门与实战
java·spring boot·spring
m0_748461392 小时前
Spring Boot + Vue 项目中使用 Redis 分布式锁案例
vue.js·spring boot·redis
山东小木2 小时前
JBoltAI需求分析大师:基于SpringBoot的大模型智能需求文档生成解决方案
人工智能·spring boot·后端·需求分析·jboltai·javaai·aigs
Moonbit2 小时前
MoonBit 再次走进清华:张宏波受邀参加「思源计划」与「程序设计训练课」
前端·后端·编程语言
RestCloud2 小时前
一站式数据集成:iPaaS 如何让开发者和业务人员都满意?
前端·后端·架构
稻草猫.2 小时前
Java多线程(一)
java·后端·java-ee·idea
Java中文社群3 小时前
炸裂:SpringAI新版发布,终于支持断线重连了!
java·后端·ai编程