Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use app.listen with Socket.io in Node?

This is my node.js code for the index.js file.

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);

However, the server is not emitting the data as specified in the timer function. Can you help me fix this? Is there a way to use app.listen with it?

Followed a few tutorial. It was working fine a couple of days ago. Then, I changed something that messed the thing up. I guess I have to figure out what I changed. Any solution?

like image 531
joler-botol Avatar asked Nov 23 '25 12:11

joler-botol


1 Answers

If you want to run socket.io on the same port as webserver, you can try this:

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

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

http.listen((process.env.PORT || 3000), () => {
    console.log('Started');
});
like image 118
IchigoWalker Avatar answered Nov 25 '25 09:11

IchigoWalker