【Spring Web教程】SpringBoot 整合WebSocket

本文介绍了如何在SpringBoot应用中集成WebSocket,实现服务端与前端的双向通信。通过引入相关依赖,创建WebSocket处理器和路由,以及编写前端JavaScript代码,建立WebSocket连接。同时,提供了测试类用于服务端向所有连接的客户端发送消息。WebSocket常用于聊天室、通知、物联网通讯等场景。
摘要由CSDN通过智能技术生成

概括

WebSocket是一种服务端和网页之间的通讯协议,服务端跟网页保持着长连接,可以达到服务端主动给网页发消息的功能。

常用场景:Web聊天室、通知和紧急告警、网页消息通信、物联网通讯。

SpringBoot整合WebSocket

步骤:

1.导入WebSocket依赖

2.编写WebSocket处理器

3.编写WebSocket处理器路由

4.编写前端代码

导入WebSocket依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

编写WebSocket处理器路由

import lombok.extern.java.Log;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket处理器
 * @version 1.0
 * @author terry
 * @date 2022/7/4
 */
@Component
@Log
public class WebSocketHandler implements org.springframework.web.socket.WebSocketHandler {

    public static Map<String, WebSocketSession> sshMap = new ConcurrentHashMap<>();

    /**
     * 用户连接上WebSocket的回调
     * @param webSocketSession
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) {
        log.info("用户 连接WebSocket");
        sshMap.put(UUID.randomUUID().toString(), webSocketSession);
    }

    /**
     * 收到消息的回调
     * @param webSocketSession
     * @param webSocketMessage
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) {
        log.info("用户发送消息");
    }

    /**
     * 出现错误的回调
     * @param webSocketSession
     * @param throwable
     */
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) {
        log.info("数据传输错误");
    }

    /**
     * 连接关闭的回调
     * @param webSocketSession
     * @param closeStatus
     */
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) {
        log.info("用户断开连接");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

编写WebSocket处理器路由

import com.terry.handler.WebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * websocket 配置
 * @version 1.0
 * @author terry
 * @date 2022/7/4
 */
@Configuration
@EnableWebSocket
public class WebSSHWebSocketConfig implements WebSocketConfigurer{
    @Autowired
    WebSocketHandler webSocketHandler;
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        //socket通道
        //指定处理器和路径
        webSocketHandlerRegistry.addHandler(webSocketHandler, "/websocket")
                .setAllowedOrigins("*");
    }
}

编写前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket demo</title>
</head>
<body>
</body>
<script>
       let socket = new WebSocket("ws://localhost:8080/websocket");
        //打开事件
        socket.onopen = function() {
            console.log("websocket已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        socket.onmessage = function(msg) {
            document.write("<p>" + msg.data + "</p>")
            //发现消息进入    开始处理前端触发逻辑
        };
        //关闭事件
        socket.onclose = function() {
            console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            console.log("websocket发生了错误");
        }
</script>
</html>

测试类发送消息

import com.terry.handler.WebSocketHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;

/**
 * 测试发送消息
 * @author terry
 * @version 1.0
 * @date 2022/7/11 16:44
 */
@Controller
public class TestCtrl {

    @RequestMapping("/testWebSocket")
    @ResponseBody
    public String testWebSocket(){
        WebSocketHandler.sshMap.forEach((k, v) -> {
            TextMessage textMessage = new TextMessage(" Hello websocket ! ");
            try {
                v.sendMessage(textMessage);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        return "发送成功!";
    }

    @RequestMapping("/")
    public String index(){
        return "index";
    }
}

打开前端界面效果

image-20220725215331598

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

terrybg

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

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

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

打赏作者

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

抵扣说明:

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

余额充值