简体   繁体   中英

How to setup Socket.io for listen separate pages with Express NodeJS

I have the next server.js file structure, where I have two pages and only for last /chat page I need to implement the event listener by Socket.io library:

'use strict'

const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);

const index = require('./routes/index');
const chat = require('./routes/chat');

app.use('/', index);
app.use('/chat', chat);

// sockets.io code part start...
app.use((req, res, next) => { 
    res.locals['socketio'] = io; 
    next(); 
});
// sockets.io code part finish...

const port = process.env.API_PORT || 8989;
server.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

What I get by this structure? My server listen all enters on the site by localhost:3000 and localhost:3000/chat , that is a wrong. So, I think I need to implement my part of code that responce for handling sockets.io events in the specific route /chat ...

I had the next chat.js file in my routes system:

const express = require('express');
const router = express.Router();

router.use(function timeLog(req, res, next) {
    console.log('Time: ', Date.now());
    next();
});

router.route('/chat')
    .get((req, res) => {
        let messages = [];
        let userCounter = 0;
        let users = [];

        const io = res.locals['socketio'];
        io.on('connect', (socket) => {
            console.log('Connection established!');
            socket.on('new user', (message) => {
                userCounter++;
                users.push(userCounter)
                console.log('New user is in! Count of users online:', users)
            });

            socket.emit('new connect', messages);

            socket.on('message data', (message) => {
                console.log(message);
                messages.push(message);
                io.emit('New message:', message);
            });
        });
        res.json('Hello on the Chatpage!');
    });

module.exports = router;

How can I implement sockets.io in my case only for /chat page without global invoke of socket.io library in server file or it's impossible? I need any help...

Thank you!

You can separate your socket related code by following way :

==>app.js

var express = require('express');
var socket = require('./socketServer');
var app = express();
var server = app.listen(3000, function () {
    console.log('Listening on port 3000 ...');
});
socket.socketStartUp(server);
module.exports = app;

==>socketServer.js

var io = require('socket.io')();
var socketFunction = {}
socketFunction.socketStartUp = function (server) {
    io.attach(server);
    io.on('connection', function (socket) {
        console.log("New user is connected with socket:", socket.id);
    })
}
module.exports = socketFunction;

You can also check node API startup code with socket functionality in below link:

click here

Hope this answer is helpful to you

Update your code accordingly:

    // Declare socket.io
    const io = require('socket.io')(server);

    // Set middleware
    app.use((req, res, next)=>{ res.locals['socketio'] = io; next(); });

    // Later in a chat route
    router.get('/chat', (req, res, next)=>{
      const io = res.locals['socketio']
    });

Hope this solves your query.

问题是您必须将HTTP连接升级为websocket连接,因此仍需要在主页中使用socket.io。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM