如何在Node中的Socket.io中使用app.listen?

时间:2019-03-10 09:28:11

标签: node.js express socket.io

这是我的 index.js 文件的node.js代码。

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const { mongoose } = require('./config/db.js');
var routes = require('./routes/routes');
var j = require('./utility/mailer');
var app = express();



//app.use(bodyParser.json());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));

app.use(cors({ origin: 'http://localhost:4200' }));
app.use(express.static('uploads'));
//app.listen(3000, () => console.log('server started'));
app.use(function (req, res, next) {
    res.setTimeout(10000, function () {
        console.log('timeout call');
        res.status(408).send({ 'res': 'timed out' });
        //res.end(408);
        return;
    });
    next();
});
app.use('/', routes);

app.set("port", (process.env.PORT || 3000));
//app.listen(app.get("port"), function () {
// console.log("Server started: http://localhost:" + app.get("port") + "/");
//})
//var server = app.listen(app.get('port'), function () {
//   console.log('Express server listening on port ' + server.address().port);
//});

var server = app.listen(3000);

var io = require("socket.io").listen(server, {
    handlePreflightRequest: (req, res) => {
        const headers = {
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
            "Access-Control-Allow-Origin": req.headers.origin,
            "Access-Control-Allow-Credentials": true
        };
        res.writeHead(200, headers);
        res.end();
    }
});

let timerId = null,
    sockets = new Set();
io.sockets.on('connection', socket => {

    sockets.add(socket);
    console.log(`Socket ${socket.id} added`);

    if (!timerId) {
        startTimer();
    }

    socket.on('clientdata', data => {
        console.log(data);
    });

    socket.on('disconnect', () => {
        console.log(`Deleting socket: ${socket.id}`);
        sockets.delete(socket);
        console.log(`Remaining sockets: ${sockets.size}`);
    });

});
function startTimer() {
    //Simulate stock data received by the server that needs 
    //to be pushed to clients
    timerId = setInterval(() => {
        if (!sockets.size) {
            clearInterval(timerId);
            timerId = null;
            console.log(`Timer stopped`);
        }
        let value = ((Math.random() * 50) + 1).toFixed(2);
        //See comment above about using a "room" to emit to an entire
        //group of sockets if appropriate for your scenario
        //This example tracks each socket and emits to each one
        for (const s of sockets) {
            console.log(`Emitting value: ${value}`);
            s.emit('data', { data: value });
        }

    }, 2000);
}
var gulp = require('gulp');
var sonarqubeScanner = require('sonarqube-scanner');

gulp.task('default', function (callback) {
    sonarqubeScanner({
        serverUrl: "https://localhost:8081",
    }, callback);
});
io.listen(8000);
//server.listen(8080);

但是,服务器未按照计时器功能指定的方式发送数据。你能帮我解决这个问题吗?有没有办法使用app.listen?

跟随一些教程。几天前工作正常。然后,我改变了一些东西弄乱了东西。我想我必须弄清楚自己做了什么。有解决办法吗?

2 个答案:

答案 0 :(得分:1)

如果要在与Web服务器相同的端口上运行socket.io,可以尝试此操作。

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

const io = require('socket.io')(http);

io.on('connection', (socket) => {
    //your code here
})

const server = http.listen(process.env.PORT || 3000, () => {
      console.log('Started');
});```

答案 1 :(得分:0)

我声明变量 port 将是您将在其上托管服务器的端口 const port = 3000; (端口号可以是您喜欢的任何内容)。然后添加使服务器侦听的代码:

server.listen(port, () => {
    // What will happen when the server starts listening
});

虽然,您需要在显示 server.listen() 的地方声明服务器变量,如果您正在做一个简单的 http 服务器,您可以这样说:

const server = http.createServer((req, res) => {
    // What the server would do
});

此外,您需要声明 const server = http.createServer() 中的 http 内容。您需要做的是添加一段代码来说明 http 是什么,例如 const http = require('http');。这将使一个简单的 http 服务器侦听 http://localhost:your port/。最终产品应如下所示:

const http = require('http');

const port = 3000;

const server = http.createServer((req, res) => {
    // Your Code Here
});

server.listen(port, () => {
    // Your Code Here
});

然后,在您的终端中输入 node index.js 这应该会启动您的服务器,并且可以在您的浏览器上看到它!!

注意:此代码对于您正在执行的操作可能过于简单,但可能会起作用