向所有客户端广播一个基本事件

Broadcast a basic event to all clients

我将如何在当前可用的所有客户端上广播 alert("Hello World!");
我浏览了这些链接:

  • https://socket.io/get-started/chat
  • https://socket.io/docs/v3/client-api/
  • https://socket.io/docs/v3/emit-cheatsheet/
  • 其中 NONE 提供了帮助。有人可以帮帮我吗?!

    我尝试过的解决方案:

    // Script.js:
    var socket;
    
    function onload(){
      socket = io();
    }
    
    function test(){
       socket.emit("broadcast");
    }
    socket.on('broadcast', function() {
        alert("Hello World!");
    });
    
    // index.js:
    const express = require("express");
    const socketio = require("socket.io");
    const path = require("path");
    const app = express();
    const http = require("http");
    const io2 = require("socket.io-client");
    
    const directory = path.join(__dirname, "html");
    const httpserver = http.Server(app);
    const io = socketio(httpserver);
    
    app.use(express.static(directory));
    httpserver.listen(3000);
    
    
    

    要从您的服务器向所有连接的客户端广播消息,您需要:

    io.emit('bulletin', someMsg);
    

    要在客户端中收听该消息,您可以这样做:

    socket.on('bulletin', someMsg => {
        console.log(someMsg);
    });
    

    消息名称 'bulletin' 可以是您想要的任何名称(任何不与 built-in 消息名称冲突的字符串)。

    您不能直接从客户端触发广播。但是,您可以向服务器发送您设计的自定义消息,并让服务器在收到该消息后向所有连接的客户端进行广播。