前端websocket和后端传输数据
前言:用户在页面添加内容以后,通过接口将数据存储在大数据工程师哪儿,大数据哪儿把文件处理以后传输给后端java工程师,java工程师将添加的该条信息需要及时传递给用户,让用户进行下载。websocket在整个流程中负责前后端数据的传递,及后端将数据传输给前端,前端进行展示,提示用户随时下载所需要下载的内容。
图一、用户在此添加数据然后点击发布,数据存储进后端大数据
数据存进系统大数据进行处理过后,后端和前端通过websocket实时传输
前端需要做的创建websocket,其中可以给后端发送数据,也可以接收后端返回的数据
<template> <div class="test"></div> </template> <script> export default { name : WebSocket, data() { return { websock: null, } }, created() { this.initWebSocket(); }, destroyed() { this.websock.close() //离开路由之后断开websocket连接 }, methods: { initWebSocket(){ //初始化weosocket // const userId = window.sessionStorage.getItem(userId) const wsuri = "ws://127.0.0.1:8080/webSocket/" + userId; //此处访问后端服务 this.websock = new WebSocket(wsuri); this.websock.onmessage = this.websocketonmessage; // this.websock.onopen = this.websocketonopen; this.websock.onerror = this.websocketonerror; this.websock.onclose = this.websocketclose; }, websocketonopen(){ //连接建立之后执行send方法发送数据 let actions = {"test":"李狗蛋"}; this.websocketsend(JSON.stringify(actions)); }, websocketonerror(){ //连接建立失败重连 this.initWebSocket(); }, websocketonmessage(e){ //数据接收 const redata = e.data console.log(redata) }, websocketsend(Data){//数据发送 this.websock.send(Data); }, websocketclose(e){ //关闭 console.log(断开连接,e); }, }, } </script> <style lang=less> </style>
下一篇:
必须有数字和字母组合的密码正则表达式