首先发几个参考文档
webSocket 简介
首先,WebSocket是一种通信协议,区别于HTTP协议,HTTP协议只能实现客户端请求,服务端响应的这种单项通信。
而WebSocket可以实现客户端与服务端的双向通讯,说白了,最大也是最明显的区别就是可以做到服务端主动将消息推送给客户端。
其余的特点有:
- 握手阶段采用 HTTP 协议。
- 数据格式轻量,性能开销小。客户端与服务端进行数据交换时,服务端到客户端的数据包头只有2到10字节,客户端到服务端需要加上另外4字节的掩码。HTTP每次都需要携带完整头部。
- 更好的二进制支持,可以发送文本,和二进制数据
- 没有同源限制,客户端可以与任意服务器通信
- 协议标识符是ws(如果加密,则是wss),请求的地址就是后端支持websocket的API。
webSocke 创建实例
服务端:首先在node服务端,首先需要使用如下语句安装拓展
cnpm install express express-ws -S
客户端创建webSocket请求连接
<template> <div class="websocket"> <textarea cols="50" rows="20" v-model="requireData"></textarea> <el-button type="primary" @click="connectWebScket">连接到服务器webSocket</el-button> <el-button type="danger" @click="closeConnect">关闭连接</el-button> </div> </template> <script> export default { data() { return { websock: null, //用于初始化为一个webSocket实例 requireData: "接收到服务端发送的数据:" //用于接收服务器返回的数据 }; }, destroyed() { //销毁组件,跳转路由时关闭webSocket连接 this.websock.close(); }, methods: { //连接到webSocket connectWebScket() { this.initWebSocket(); }, //关闭连接 closeConnect() { this.websock.close(); }, initWebSocket() { //初始化weosocket // 以 ws://服务器地址/webSocket 路由的形式建立连接 const wsuri = "ws://127.0.0.1:8081/test"; 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; }, //连接建立之后执行send方法发送数据 websocketonopen() { let actions = { sendCustomData: "建立连接后,客户端自动发送数据****到服务端" }; this.websocketsend(actions); }, //连接建立失败重连 websocketonerror() { this.initWebSocket(); }, //接收服务端数据 websocketonmessage(e) { const redata = e.data; this.requireData = this.requireData + "\n" + redata; console.log("接收到服务端发送的数据:", redata); }, //客户端发送数据 websocketsend(Data) { this.websock.send(Data); }, //关闭webSocket连接 websocketclose(e) { console.log("关闭webSocket连接:", e); } } }; </script> <style scoped> </style>
效果图:
扫描二维码关注公众号,回复: 9133084 查看本文章