【问题标题】:Event emmission doesn't work io.sockets.emit()事件发射不起作用 io.sockets.emit()
【发布时间】:2019-11-23 07:28:02
【问题描述】:

尝试为整个套接字连接和所有连接到套接字的客户端发出事件。 用过,

io.sockets.emit('toALL',{msg: 'this is demo'});

并在index.html 中使用以下代码行处理它:

socket.on("toALL",function(){
   // If console is putted here still not able to get any msg or response from emit. 
});

【问题讨论】:

    标签: node.js sockets events socket.io emit


    【解决方案1】:

    您发送到套接字的对象可用作.on 的回调函数的参数。您可以使用io.emit 向所有客户端广播。

    // server
    io.emit("toALL", {msg: "this is demo"});
    
    // client
    socket.on("toALL", function (msg) {
      console.log(msg); 
    });
    

    【讨论】:

    • 在客户端我是否需要使用带有前缀 http 的 url 调用函数 connect()?我在 http 上运行我的服务器并使用,var socket = io() 在客户端,client.html 文件。
    • 不一定——如果你不提供参数,它假定相同的域,这可能是也可能不是你需要的。如果无法连接,您应该会收到一个错误(您应该与我们分享)。
    【解决方案2】:

    我的解决方案来自:https://socket.io/get-started/chat#Integrating-Socket-IO

    对于server.js:

    io.on('connection', function(socket){
       socket.on('toALL', function(msg){
         io.emit('toALL', msg);
       });
     });
    

    对于客户端.html

    socket.emit('toALL', 'event');
        socket.on('toALL', function(msg){
          alert(msg);
        });
    

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多