执门文章
前端vue与springboot通信使用websocket实验
于 2023-12-15 07:33:30 发布
访问463
收藏1
文章标签:
websocker

WebSocket是HTML5下一种新的协议,它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯的目的

在很多项目中,都要用到websocket,使得前端页面与后端页进行实时通信,例如,实时查询订单状态、设备状态实时显示到页面。本博文,分为前端页面代码和后端页面代码,在最后有源代码下载链接。前端使用用vue技术,后端使用springboot

一、后端代码

1、websocket代码


@Slf4j
@Component
@ServerEndpoint(value = "/websocket/order")
public class WebsocketProvider {
 
    /**
     * 连接事件,加入注解
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        String orderId = WebsocketUtil.getParam(WebsocketUtil.sessionKey, session);
        log.info("Websocket连接已打开,当前orderId为:"+orderId);
        // 添加到session的映射关系中
        WebsocketUtil.addSession(orderId, session);
        //测试发送消息
        WebsocketUtil.sendMessage(orderId, AjaxResult.success("恭喜,已建立连接"));
    }
 
    /**
     * 连接事件,加入注解
     * 用户断开链接
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        String orderId = WebsocketUtil.getParam(WebsocketUtil.sessionKey, session);
        // 删除映射关系
        WebsocketUtil.removeSession(orderId);
    }
 
    /**
     * 当接收到用户上传的消息
     * @param session
     */
    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("收到Websocket消息:"+message);
    }
    /**
     * 处理用户活连接异常
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        try {
            if (session.isOpen()) {
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        throwable.printStackTrace();
    }
}

2、controller发送代码

@Slf4j
@RestController
@RequestMapping("/send")
@Api(tags = "SendController", description = "发送管理")
public class SendController {
    /**
     * 相关信息
     *
     */
    @GetMapping
    public String getPayType(String data) {
        WebsocketUtil.sendMessage("123456", AjaxResult.success(data));
        return "发送成功";
    }
}

3、后端向前端发送消息代码

/**
     * 根据用户ID发送消息
     *
     * @param result
     */
    public static void sendMessage(String sessionId, AjaxResult result) {
        sendMessage(sessionId, JSON.toJSONString(result));
    }
 
    /**
     * 根据用户ID发送消息
     *
     * @param message
     */
    public static void sendMessage(String sessionId, String message) {
        Session session = ONLINE_SESSION.get(sessionId);
        //判断是否存在该用户的session,判断是否还在线
        if (session == null || !session.isOpen()) {
            return;
        }
        sendMessage(session, message);
    }

二、VUE前端代码

1、界面代码

<div style="display: flex;">
			<el-input v-model="sendData" placeholder="请输入要发送的内容"/>
			<el-button type="success" @click="send" style="margin-left: 20px;">发送</el-button>
		</div>
		<div style="margin-top: 25px;margin-bottom: 5px;font-weight: bold;">收到的消息:</div>
		<div v-for="(item,index) in messages">
			<span>{{item}}</span>
		</div>

2、websocket相关代码

        console.log('进入状态监听*******')
		var url = payServerUrl+"?orderId="+orderId;
		//建立webSocket连接
		proxy.websocket = new WebSocket(url);
		//打开webSokcet连接时,回调该函数
		proxy.websocket.onopen = () =>{
			console.log("连接建立");
		} 
		//关闭webSocket连接时,回调该函数
		proxy.websocket.onclose = () =>{
			console.log("连接关闭");
		} 
		//接收信息
		proxy.websocket.onmessage = function (res) {
			var obj = eval('(' + res.data + ')');
			console.log(obj)
			proxy.messages.push(res.data)
		}

三、测试

1、后端服务启动,运行ServerApplication (运行前,maven先下载依赖包)

前端vue与springboot通信使用websocket实验

2、前端服务启动

window,运行cmd命令,进行前端页面文件夹,执行如下命令

(1)1、安装依赖包
npm install
(2)、启动服务
npm run dev

前端vue与springboot通信使用websocket实验

前端vue与springboot通信使用websocket实验

打开页面 :http://localhost:6080/#/index

前端vue与springboot通信使用websocket实验

3、前端页向后端发送数据

前端vue与springboot通信使用websocket实验

4、后端向前端页面发送数据

​使用apifox来发发送请求,apifox百度下载即可
GET请求,http://localhost:8080/ck/send,数据为data

前端vue与springboot通信使用websocket实验

四、源代码:

链接:https://pan.baidu.com/s/1YnuBFQBt2O4GIdcs4jO1SA?pwd=8ahq

提取码:8ahq



于 2023-12-15 07:33:30 发布
访问463
收藏1

实力雄厚的技术网站

产品

概述

资源

文档

版权问题

请联系客服

联系我们

联系我们


© 财瑞智能科技 2024蜀ICP备2023018175号-2川公网安备51011202000656号