zoukankan      html  css  js  c++  java
  • socket.io的使用(vue)

    最近做了点新鲜玩意,使用socket.io进行一个pk答题的开发;功能大概就是两个人在规定时间进行答题得分,越快回答分数越高;

    使用这个需要服务端一起配合使用的哦,不然用不了的;我们开发的时候后端就花了好多时间搞这个,我也不知道为啥;

    有个问题要说下,好像这个有版本问题,太高的版本,和服务端连接不起来。我们开发时用的版本是"socket.io": "2.3.0","socket.io-client": "2.3.0",

    安装:

    npm install socket.io

    引入:

    import io from 'socket.io-client';

    使用:

    connect () {
        var opts = {
            query: {
                params1: value1,
                params2: value2,
                transport: 'websocket'
            },
            path: data.split('|')[1] // 后端返回的地址 https://test.crc.com|/socket-io1 'socket-io1'
        };
        this.socket = io(env[process.env.MODE].VUE_APP_SOCKET_URL, opts);
        // 进行socket连接
        this.socket.on('connect', () => {
            console.log("连接成功");
        });
        // 监听socket推送事件 这里是后端给的事件名 'push_event'
        this.socket.on('push_event', (resData) => {
            try {
                // socket数据推送回来 做相应的处理
            } catch (err) {
                console.log('err', err)
            }
        });
        // 断开socket连接
        this.socket.on('disconnect', () => {
            console.log("disconnect");
        });
        // socket连接错误
        this.socket.on('connect_error', (error) => {
            try {
                this.socket.close()
            } catch (err) {
                console.log('err', err)
            }
        });
        // 触发尝试重新连接
        this.socket.on('reconnect_attempt', () => {
            this.socket.io.opts.transports = ['websocket'];
        });
    }
    // 给服务端发送消息
    send (data) {
        // 要发送的参数
        const sendData = {
            'id': '123',
            'data': {
                'matchId': this.opponentUserInfo.matchId+'', // 对局id
                'clientId': this.pkUserInfo.userId+'', //用户玩家id
                'questionNum': this.serveReturnQuestionData.questionNum+'',//第几题
                'option': data+'' // 选择的选项
            }
        }
        // 'text'后端给的事件名 注意传的参数要stringify下
        this.socket.emit('text',JSON.stringify(sendData));
    }

    附上文档地址:socket.io 概述_w3cschool

  • 相关阅读:
    LeetCode Single Number
    Leetcode Populating Next Right Pointers in Each Node
    LeetCode Permutations
    Leetcode Sum Root to Leaf Numbers
    LeetCode Candy
    LeetCode Sort List
    LeetCode Remove Duplicates from Sorted List II
    LeetCode Remove Duplicates from Sorted List
    spring MVC HandlerInterceptorAdapter
    yum
  • 原文地址:https://www.cnblogs.com/qiufang/p/15049159.html
Copyright © 2011-2022 走看看