Jump to content
  • Advertisement
  • entries
  • comments
  • views

Javascript Emit and Broadcast JSON



I will show differences between "emit" and "broadcast" on server side.

In short:

  • "emit" sends JSON data to a connected client
  • "broadcast" sends JSON data to every client except the connected client

At first time create a connection between the server and the client using this instruction: 101. Socket.io Connection, JS/ES5

We have this callback function in "app.js":

io.sockets.on("connection", function(socket)
    console.log("client was connected");

We will generate a name for a connected client on the server side. Client will get his own name from the server and will show it on the screen in a browser. We will use "shortid" module for generation names for clients.

Install "shortid" package. Type this command in the console from your project folder: npm install --save shortid

We will use "shortid" module to generate a random unique name. Let's show generated name:


var shortid = require('shortid');

io.sockets.on("connection", function(socket)
   var clientName = shortid.generate();
    console.log("client was connected, name = " + clientName);

You will see a message in the console, like this:


client was connected, name = 3fPIOl61W

Let's create two buttons: "Get My Name" and "Send my Name to all Clients". Copy this code to server and to client sides. Do not forget to run the server by command: node app.js After this you need to open two clients in different browser tabs: http://localhost:8080/. Open the browser console, for example in Chrome: "Ctrl+Shift+J" and clear "cache" by RMB on "Reload" button and select "Empty Cache and Hard Reload". And do not forget reload the server when you made changes on the server side code.


var express = require("express");
var app = express();
var server = require("http").Server(app);

app.get("/", function(req, res)
    res.sendFile(__dirname + "/client/index.html");
app.use("/client", express.static(__dirname + "/client"));

var port = 8080;
console.log("Server started. Port = " + port);

var io = require("socket.io")(server, {});
var shortid = require('shortid');

io.sockets.on("connection", function(socket)
    var clientName = shortid.generate();
    console.log("client was connected, name = " + clientName);

    socket.on("getMyName", function()
        socket.emit("onGetMyName", { name: clientName });

    socket.on("sendMyNameToAllClients", function()
        socket.broadcast.emit("onSendMyNameToAllClients", { name: clientName });


<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <title>Multiplayer Snake</title>

    <button onclick="getMyName();">Get My Name</button>
    <button onclick="sendMyNameToAllClients();">Send my Name to all Clients</button>
        var socket = io();

        socket.emit("hello", { message: "hello from client!" });

        socket.on("onGetMyName", function(data)
            console.log("My Name: " + data.name);

        socket.on("onSendMyNameToAllClients", function(data)
            console.log("Name of another client: " + data.name);

        function getMyName()

        function sendMyNameToAllClients()



1 Comment

Recommended Comments

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
  • Advertisement
  • What is your GameDev Story?

    In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

    (You must login to your GameDev.net account.)

  • Blog Entries

  • Similar Content

    • By CR1SPY
      Hi, I am a 13 year old and I've been playing games for practically my entire life, and I am thinking about getting into game development as my career. However I am worried about for one the pay, and if I will be able to support myself. And two if I will even be able to get a job in the industry because obviously a lot of people would want to get a job in this field and it will be very competitive. I have already started fiddling with unity and i really like it, so its not a matter of resources or if I enjoy it. So i guess my question for someone who is already in the industry is was it worth it? And if so do you have any tips or advise on how to get a good job as a game developer. Thanks in advance..
    • By Accelor
      I've been dabbling in programming for quite a while nothing professional, and the reason for that is cause I've always wanted to create games, so while learning I decided a game engine would be the better option and learned unity and I'm able to create some pretty cool stuff like an inventory system the code might not be the best but it works exactly how I visioned it too, but lately I've been wanting to learn how to create everything that makes up a game, like Collisions,Entity system we if go that route, Input system and things like that in Monogame since u basically have to implement all that stuff yourself but what I've realized is that I honestly don't know how to do ANYTHING I almost feel like I don't even know how to program it makes me super demotivated/depressed, I tried to create an Input system Idek where to start its like  im staring at the screen for 4 hours and realized I didnt do anything cause Im lost, I wanna learn how to create good systems too like for input being able to remap to different keys, having multiple keys for an input so keyboard a and keyboard o and gamepad a would be all on the same action things like that, does anyone have tips / book recommendations or anything of the sort for these kinds of things? and how did you learn how to do these things if u can?
    • By chell
      I am currently in school for Game Development and for an assignment I have to make a prototype that showcases my writing skills. I am developing a choice based Twine game as my prototype but I have a few questions. The basic premise is focusing on the emotional consequences and traumas of fighting in a mech during war time.

      How long should the prototype be in order to showcase my writing skills?

      Should I include any limited art? I am not good at developing 2D art assets and I'm worried that adding some might detract from writing. 
    • By KPK
      Hello! I am a bit new to this, so pardon my etiquette. I am a student who is currently learning the basics of programming with C++ and I intend on expanding my knowledge further outside what my classes will be teaching me as I make my way towards an Engineering degree. I would like to throw my hat in on my spare time to learn to program 2D games that are based in C++, but I do not know where exactly to start doing so, particularly in the area of what software I need and can get to turn the limited black-background-white-text output from "Windows Visual Studio 2017" to generating the images/menus/sounds/visuals/controller-input needed to at least have the basic tools required to make a game.
      So, long story short: what software do I need to start programming a video game? Where can I get it? Any advice, tutorial links, or input would be much appreciated! Thanks!
    • By NElizabeth
      Hello everyone!  
      My name is Nicole and I am a software developer and artist whose main interest lies in browser based games and websites.  I recently released my first game and I am looking for feedback, play testers, and possibly some other game developers who might be interested in taking advantage of some of the program's unique features - such as cross-site trading, achievement tracking, events, and more!
      Collectry.com is a game about collecting items.  Items are assigned a rarity and grouped into series, similar to baseball cards.  Users can purchase a random item from a series, and the result is determined by luck and "karma" (users get a luck boost when they gift items to other users).  The goal of this casual game is collect anything and everything that piques your interest, hopefully discovering new games, artists, and products in the process!  Selling a completed series results in more tickets than would be earned by selling all the items individually, and may unlock other items or special features in the future.
      Users can even upload their own series! 
      (Items should be PNG images with transparent backgrounds - I am aware that other file types will result in errors - need to fix this)
      Feel free to register an account and poke around the site.  You will need to pardon the appearance - I was focusing on core functionality, not page design.
      In itself, the game is not really something that you could binge play for hours.  The real excitement stems from the fact that Collectry is an OAuth2 resource and authentication server and can interact with 3rd party websites, games, and organizations. 
      3rd parties will be able to let users link their Collectry accounts to their game, then use the API to check the player's items - upon which they can award special in-game items for completing the entire series or obtaining a particular item.  Games also have the ability to "send" items to Collectry, allowing users to earn event items, keep track of achievements, or as a mechanism for cross-site trading.
      The game is still being developed and can be tailored to other use-cases if needed!
      I appreciate you taking the time to check out Collectry.com and look forward to answering any questions you might have! 
      Any and all feedback is appreciated!
      If you are interested in taking advantage of the OAuth2 functionality, please comment here or send a message to alpha@collectry.com.

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!