Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
React Components

You're reading from  React Components

Product type Book
Published in Apr 2016
Publisher
ISBN-13 9781785889288
Pages 182 pages
Edition 1st Edition
Languages
Author (1):
Christopher Pitt Christopher Pitt
Profile icon Christopher Pitt

Communicating through web sockets


Sometimes, it's better to have fast, bi-directional communication between the browser and the server.

At such a time, you can try web sockets. They're an upgrade to the traditional HTTP communication seen in Ajax. To work with them easily, we need the help of Socket.IO:

npm install --save socket.io

Now we can access a new object, which we'll call io:

// ...enable JSX/ES6 compilation

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

app.get("/", function (request, response) {
    response.send(
        require("./hello-world")
    );
});

// ...define other endpoints

io.on("connection", function (socket) {
    console.log("connection");

    socket.on("message", function (message) {
        console.log("message: " + message);

        io.emit("message", message);
    });
});

server.listen(3000);

Note

The "message" can be anything. You can send messages of different types simply by changing this...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}