Reader small image

You're reading from  React Components

Product typeBook
Published inApr 2016
Publisher
ISBN-139781785889288
Edition1st Edition
Tools
Right arrow
Author (1)
Christopher Pitt
Christopher Pitt
author image
Christopher Pitt

Christopher Pitt is a principal developer for SilverStripe in Wellington, New Zealand. He usually works on open source software, though sometimes you'll find him building compilers and robots.
Read more about Christopher Pitt

Right arrow

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 page is locked
Previous PageNext Page
You have been reading a chapter from
React Components
Published in: Apr 2016Publisher: ISBN-13: 9781785889288

Author (1)

author image
Christopher Pitt

Christopher Pitt is a principal developer for SilverStripe in Wellington, New Zealand. He usually works on open source software, though sometimes you'll find him building compilers and robots.
Read more about Christopher Pitt