目标
-
继承webSocket, 和后台建立通道
-
完成效果
步骤
-
安装客户端socket的包(支持websocket) - 内部对websocket进行了封装
npm i socket.io-client@4.0.0
-
在Chat/index.vue引入包
// 导入 socket.io-client 包 import { io } from 'socket.io-client'
data () { return { // 定义变量,存储 websocket 实例 socket: null } },
-
创建socket服务
created () { // 创建客户端 websocket 的实例 this.socket = io('http://toutiao.itheima.net', { query: { token: this.$store.state.user.token }, transports: ['websocket'] }) }
-
监听是否连接成功
只有连接内置事件执行了, 才能进行后续操作
created () { // 建立连接的事件 this.socket.on('connect', () => { console.log('与服务器建立了连接') }) }
-
在组件销毁前, 关闭服务
// 组件被销毁之前,清空 sock 对象 beforeDestroy () { // 关闭连接 this.socket.close() // 销毁 websocket 实例对象 this.socket = null }
-
在created监听socket的消息
created() { // ... // 接收到消息的事件 socket.on('message', data => { // 把服务器发送过来的消息,存储到 list 数组中 this.list.push({ name: 'xs', msg: data.msg }) }) },
-
在 send事件中, 把服务器发来的数据装到数组里
methods:{ sendFn () { // 判断内容是否为空 if (!this.word) return // 添加聊天消息到 list 列表中 this.list.push({ name: 'me', msg: this.word }) } }
-
客户端调用
socket.emit('message', 消息内容)
方法把消息发送给 websocket 服务器:// 向服务端发送消息 sendFn () { // 判断内容是否为空 if (!this.word) return // 添加聊天消息到 list 列表中 this.list.push({ name: 'me', msg: this.word }) // 把消息发送给 websocket 服务器 socket.emit('message', { msg: this.word, timestamp: new Date().getTime() }) // 清空文本框的内容 this.word = '' }
小结
-
vuecli项目中下载socket.io包
-
建立和服务器的socket连接
要到连接地址和参数等注意事项
-
与后台协商好, 发送消息和接收消息的事件名, 以及数据格式