Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
React Components

You're reading from   React Components Explore the power of React components for cutting-edge web development

Arrow left icon
Product type Paperback
Published in Apr 2016
Publisher
ISBN-13 9781785889288
Length 182 pages
Edition 1st Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
Christopher Pitt Christopher Pitt
Author Profile Icon Christopher Pitt
Christopher Pitt
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

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 $19.99/month. Cancel anytime