Search code examples
node.jssocket.ioclient

Broadcast a basic event to all clients


How would I go about broadcasting alert("Hello World!"); on all clients currently avaible?
I have gone through these links:

  • https://socket.io/get-started/chat
  • https://socket.io/docs/v3/client-api/
  • https://socket.io/docs/v3/emit-cheatsheet/
  • And NONE of them helped. Can someone please help me?!

    Solutions I have tried:

    // 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);
    
    
    

    Solution

  • To broadcast a message to all connected clients from your server, you do:

    io.emit('bulletin', someMsg);
    

    To listen for that message in the client, you do this:

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

    The message name 'bulletin' can be anything you want it to be (any string that doesn't conflict with a built-in message name).

    You cannot trigger a broadcast directly from the client. But, you can send the server a custom message that you design and have the server, upon receipt of that message, then do a broadcast to all connected clients.