一、WebSocket 简介
http请求是前端和后端的最常见的交互模式:前端发数据请求,从后端拿到数据后展示到页面中。http协议也有一个最大的缺陷,就是后端没有主动权,不能主动向前端推送数据。 ? 一种新的通信协议应运而生
WebSocket
,它最大的特点就是服务端可以主动向客户端推送消息
,客户端也可以主动向服务端发送消息,实现了真正的平等。WebSocket
的其他特点:? 1.建立在 TCP 协议之上,服务器端的实现比较容易; ? 2.与 HTTP 协议有着良好的兼容性; ? 3.默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。 ? 4,。数据格式比较轻量,性能开销小,通信高效; ? 5.可以发送文本,也可以发送二进制数据; ? 6.没有同源限制,客户端可以与任意服务器通信; ? 7.协议标识符是ws(如果加密,则为wss),服务器网址就是 URL;
二、vue中的websocket使用2.1 vue中使用 WebSocket 注意项判断浏览器是否支持WebSocket
的协议和访问;建立连接和断开连接的控制,在组件加载的时候 连接websocket,在组件销毁的时候 断开websocket;服务器后端支持,后端接口需要引入 socket 模块,否则不能实现连接;2.2 vue-socket.io安装和使用简介? 我在vue中使用的
vue-socket.io
库,vue-socket.io 其实是在 socket.io-client 基础上做了一层封装,将 $socket 挂载到 vue 实例上,同时可使用 sockets 对象轻松实现组件化的事件监听
,在 vue 项目中使用起来更方便。安装:npm i vue-socket.io
引入:// main.jsimport Vue from 'vue'import store from './store'import App from './App.vue'import VueSocketIO from 'vue-socket.io'Vue.use( new VueSocketIO({ // 生产环境建议关闭,开发环境打开(在控制台看到socket连接和事件监听的信息) debug: true, connection:'http://metinseylan.com:1992', options:{ // 创建时是否自动连接 我们这里设定为false,在指定页面再开启 autoConnect: false, // 路径(默认值:/socket.io/) path: "/my-app/", // 目前有两种传输方式:HTTP long-polling(可简称:polling)、WebSocket transports: ['polling'], // 附加请求头(在服务器端的 socket.handshake.headers 对象中找到) extraHeaders:{}, }, vuex: { store, actionPrefix: 'SOCKET_',// vuex action 前缀 mutationPrefix: 'SOCKET_', // vuex mutation 前缀 }, }))new Vue({ router, store, render: h => h(App)}).$mount('#app')
常见参数 | 类型 | 默认值 | 是否必选 | 描述 |
debug | Boolean | false | 可选择 | 为调试启用日志记录 |
connection | String / Socket.io-client | null | 必要 | Websocket 服务器 url 或 socket.io-client 实例 |
vuex.store | Vuex | null | 可选择 | Vuex store 实例 |
vuex.actionPrefix | String | null | 可选择 | 发出服务器端 vuex 操作的前缀 |
vuex.mutationPrefix | String | null | 可选择 | 发出服务器端 vuex 突变的前缀 |
<template> <div class="wrap"> <button @click="socketEmit">连接Socket</button> <button @click="socketSendmsg">发送数据</button> </div></template><script>export default { data(){ return { randomId:null, } }, methods:{ //连接socket服务器 socketEmit(){ // 打开socket连接 this.$socket.open(); // 订阅事件,testCall 是与后端约定好的名称 this.sockets.subscribe('demoCall', (res) => { if(res.code == 200 && res.randomId === this.randomId){ console.log('召唤成功') } }) }, // 发送测试消息 socketSendmsg(){ this.userid = Math.random(); // testCall 是与后端约定好的名称 this.$socket.emit('demoCall', { "userid": this.userid, "deviceId": "123456" }); }, }, sockets: { connect: function () { console.log('连接成功') }, disconnect: function () { console.log('断开连接') }, reconnect: function () { console.log('重新连接') }, }, beforeDestroy(){ // 关闭 Socket this.sockets.unsubscribe('demoCall'); this.$socket.close(); },}</script>
简单记录vue的vue-socket.io使用过程,希望对需要的各位有所帮助。