如何设置Socket.io以使用Express NodeJS监听单独的页面

时间:2018-05-20 19:16:12

标签: node.js sockets express socket.io

我有下一个server.js文件结构,我有两个页面,只有最后一个/chat页面我需要通过Socket.io库实现事件监听器:

'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}`);
});

这种结构我得到了什么?我的server收听所有人都在localhost:3000localhost:3000/chat进入网站,这是错误的。所以,我认为我需要实现我的部分代码来响应处理特定路由sockets.io中的/chat事件......

我的路线系统中有下一个chat.js文件:

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;

我如何在/chat页面中实现sockets.io而不在socket.io library文件中全局调用server,或者这是不可能的?我需要任何帮助......

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以通过以下方式分隔与套接字相关的代码:

<强> ==&GT; 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;

<强> ==&GT; 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;

您还可以在下面的链接中查看带有套接字功能的节点API启动代码:

click here

希望这个答案对你有所帮助

答案 1 :(得分:0)

相应地更新您的代码:

    // 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']
    });

希望这能解决您的问题。

答案 2 :(得分:0)

问题是你必须将HTTP连接升级到websocket连接,所以你仍然需要在主页面中使用socket.io ...