How to use sock.io within mini-routes?

18 views
Skip to first unread message

Lasse Karagiannis

unread,
Mar 14, 2016, 3:46:53 PM3/14/16
to Express
Hi, I want to emit a socket.io event within mini routes. How do I accomplish this?
In my server,js I have:

var http = require("http");
var server = http.createServer(app);

var io = require("socket.io").listen(server);
app.set("socketio",io);
app.set("server", server);
app.get("server").listen(port, function() {
    console.log("Express started on https://localhost:" + port);
    console.log("Press Ctrl-C to terminate...");
});

app.use("/", require("./routes/home.js"));
app.use("/", require("./routes/todo.js"));

});
// In this examle we just have static files
app.use(express.static(__dirname + '/public'));


// This is called every time a client is conneting
// the socket is for the client that connects
io.on('connection', function (socket) {

    // When a client call for login
    socket.on("login", function(data) {

        // Save the username in the socket object
        socket.username = data.username;
        var welcomeMessage = "Welcome to the chat " + socket.username;

        // This is sent to the one client that connected
        socket.emit("welcome", {message: welcomeMessage});
        // This is broadcast to all connected users (except the client that send this)
        socket.broadcast.emit("newUser", {message: socket.username + " has joined the chat!"});
    });

    // When a client sends a new message
    socket.on('chatMessage', function (data) {
        // Tell all clients there is a new message - Send back to the one that wrote it
        io.emit('chatMessage', {
            message: data.messageText,
            user: socket.username
        });
    });

    // Called when a socket/client is disconnecting from the WS
    socket.on('disconnect', function () {
        // echo globally that this client has left
        io.emit('userLeft', {
            user: socket.username
        });
    });
});

Then one of the mini-routes look like this:

"use strict"

// Use the express.Router class to create modular, mountable route handlers.
let router = require("express").Router();


// this will trigger on the root url (/)
router.route("/")
    .get(function(request, response) {
      
     Here I want to do, something like
         var socketio = request.app.get("socketio");
         socketio.emit("time", Date.now());

      // middleware that is specific to this router
        // render the view for the home
        response.render("home/index"); /

});
// Exports
module.exports = router;

Reply all
Reply to author
Forward
0 new messages