springboot websocket 后端与前端跨域通信

本文介绍如何使用Spring Boot搭建WebSocket服务,包括Maven依赖引入、ServerEndpointExporter配置、WebSocket服务实现及跨域配置等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、maven引入spring-boot-starter-websocket

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

二、配置 ServerEndpointExporter

/**
 * @author hyf
 * @date 2020/9/15
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

三、websocket服务


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author hyf
 * @date 2020/9/15
 */
@ServerEndpoint("/service/websocket")
@Component
public class WebSocket {

    Logger logger = LoggerFactory.getLogger(this.getClass());
    private static Map<String, WebSocket> clients = new ConcurrentHashMap<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) throws IOException {
        this.session = session;
        logger.info("websocket 已连接");
        String uuid = UUID.randomUUID().toString();
        clients.put(uuid, this);
    }

    @OnClose
    public void onClose() throws IOException {
        logger.info("websocket 已断开");
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        logger.info("websocket 推送消息:" + message);
        int n = 0;
        Iterator<Map.Entry<String, WebSocket>> it = clients.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, WebSocket> item = it.next();
            WebSocket ws = item.getValue();
            boolean open = ws.session.isOpen();
            if (!open) {
                clients.remove(item.getKey());
                continue;
            }
            ws.session.getAsyncRemote().sendText(message);
            n++;
        }
        logger.info("websocket 推送消息完成数量:" + n);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("websocket 异常:" + error);
    }
}

四、配置服务可跨域访问(我这里是filter中加了允许跨域访问,根据自身系统配置修改),权限配置中开放“/service/websocket”地址的访问

五、前端实现websocket连接和消息接收

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>test</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
    
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.1.1/sockjs.min.js"></script>
</head>
<body>

</body>
<script>



    var websocaket = null;
    if ('WebSocket' in window) {
        websocaket = new WebSocket("ws://192.168.68.100:8080/prod-api/service/websocket");
    } else {
        alert("not support");
    }
    //连接错误
    websocaket.onerror = function () {
        alert("连接错误");
    }
    //连接成功
    websocaket.onopen = function () {
        alert("连接成功");
    }
    //收到消息
    websocaket.onmessage = function (msg) {
        var num = msg.data;
        switch (num) {
            case "1":
                $("id").attr("src", "http://localhost:5581");
                break;
            case "2":
                $("id").attr("src", "https://www.baidu.com");
                break;
            default:
                $("id").attr("src", "https://www.qq.com")
                break;
        }
    }
    //连接关闭
    websocaket.onclose = function () {
        alert("连接关闭");
    }


</script>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值