如何使用 vue 套接字连接节点服务器

时间:2021-07-14 11:13:17

标签: node.js vue.js websocket socket.io

我正在使用 vue.js(Laravel) 连接我的聊天节点服务器,它的连接套接字但发出的功能不起作用。

      var socket = io.connect('http://localhost:3000/api/message');

        socket.on('connect', function () {

           var mapdata = {chatId: this.chatIdd, userId: this.userIdd}

           socket.emit("joinChat", JSON.stringify(mapdata) ,function(confirmation){
               alert('Work');

                      console.log(confirmation);
              });

        }.bind(this));
           socket.on('msgReceive', function () {


        }.bind(this));

alert('Work') 没有显示。我该如何解决?

这是服务端功能

        socket.on("joinChat", async msg => {
            let objectValue = await JSON.parse(msg);
            chatId = objectValue["chatId"];
            socket.join(chatId);
        });

1 个答案:

答案 0 :(得分:0)

要使用(确认)知识,您必须触发该函数。

客户

socket.on('connect', function() {
  socket.emit("joinChat", {
    chatId: this.chatIdd,
    userId: this.userIdd
  }, function(confirmation) {
    //alert('Work');
    console.log(confirmation); // From server
  });
}.bind(this));

服务器

socket.on('joinChat', (msg, ack) => {
  if (msg.chatId) {
    socket.join(msg.chatId);
    if (typeof ack === 'function') ack('From server')
  }
});
相关问题