小思同学_webSocket使用

目标

  • 继承webSocket, 和后台建立通道

  • 完成效果

 

步骤

  1. 安装客户端socket的包(支持websocket) - 内部对websocket进行了封装

    npm i [email protected]
  2. 在Chat/index.vue引入包

    // 导入 socket.io-client 包
    import { io } from 'socket.io-client'
     data () {
        return {
          // 定义变量,存储 websocket 实例
          socket: null
        }
      },
  3. 创建socket服务

     

    created () {
        // 创建客户端 websocket 的实例
        this.socket = io('http://toutiao.itheima.net', {
          query: {
            token: this.$store.state.user.token
          },
          transports: ['websocket']
        })
    }
  4. 监听是否连接成功

    只有连接内置事件执行了, 才能进行后续操作

    created () {
        // 建立连接的事件
        this.socket.on('connect', () => {
          console.log('与服务器建立了连接')
        })
    }
  5. 在组件销毁前, 关闭服务

     // 组件被销毁之前,清空 sock 对象
      beforeDestroy () {
        // 关闭连接
        this.socket.close()
    
        // 销毁 websocket 实例对象
        this.socket = null
      }
    
  6. 在created监听socket的消息

     

    created() {
        // ...
    
        // 接收到消息的事件
        socket.on('message', data => {
          // 把服务器发送过来的消息,存储到 list 数组中
          this.list.push({
            name: 'xs',
            msg: data.msg
          })
        })
    },
  7. 在 send事件中, 把服务器发来的数据装到数组里

    methods:{
        sendFn () {
        // 判断内容是否为空
        if (!this.word) return
     
        // 添加聊天消息到 list 列表中
        this.list.push({
            name: 'me',
            msg: this.word
        })
       }
    }
  8. 客户端调用 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 = ''
    }

小结

  1. vuecli项目中下载socket.io包

  2. 建立和服务器的socket连接

    要到连接地址和参数等注意事项

  3. 与后台协商好, 发送消息和接收消息的事件名, 以及数据格式

猜你喜欢

转载自blog.csdn.net/m0_65812066/article/details/128645378
今日推荐