【问题标题】:How to connect to socket with Socket.io-client in Vue-cli app如何在 Vue-cli 应用程序中使用 Socket.io-client 连接到套接字
【发布时间】:2018-10-30 23:27:24
【问题描述】:

所以,我正在构建一个应用程序,我必须使用套接字 URL 和 socket.io 来连接它。 我想知道在 Vue-CLI 应用程序中从客户端连接的最佳方式是什么。当我将它插入创建时,应用程序变得非常慢。

var configUrl = "CONFIG_URL";
// Axios request to retrieve socket URL
axios.get(configUrl).then((response) => {
  var socketUrl = response.data.config.liveDistributionSSL;
  var socket = io(socketUrl);

  socket.on("connect", () => {
    console.log("Connected");
    socket.emit("subscribe", {
      subscribeMode: "topSportBets",
      language: {
        default: "en"
      },
      deliveryPlatform: "WebSubscribe",
      playerUuid: null,
      subscribeOptions: {
        autoSubscribe: true,
        betCount: 3,
        excludeMeta: false,
        resubscriptions: 0,
        fullBetMeta: true,
        browser: {}
      }
    });
  });

  socket.on("message", (message) => {
    switch (message.type) {
      case "state":
        //Calling commit on an mutation to add data to it sent from socket
        commit('updateData', message.data);
        console.log("Data =>", message.data)
        break;
      case "currentMatches":
        // We have matches to update
        break;
      case "betchange":
        // We have match bets to update
        break;
    }
  });
});

我正在使用 Vuex,并且我已将此代码放入我从 Created 生命周期挂钩调用的操作中。

【问题讨论】:

    标签: sockets vue.js socket.io vuex


    【解决方案1】:

    如果我错了,有人纠正我,但我认为你不应该在操作中设置套接字连接。只有发往/来自 Socketio 的请求。

    您不需要在每次调用操作时都建立连接,Socketio 将处理连接,直到它关闭或客户端断开连接。 只需通过调用突变SOCKET_CONNECT(使用commit)来建立连接,例如从您的主 Vue 文件中。

    请看下面的例子:https://github.com/MetinSeylan/Vue-Socket.io

    【讨论】:

    • 我明白,但我没有使用 Vue-socket,只是使用 Socket.io。这些是任务的条款。我对 Socket.io 并没有真正的经验。
    猜你喜欢
    • 2022-11-10
    • 1970-01-01
    • 2015-04-06
    • 2015-11-23
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多