0
votes

I have developed a node application which is running in port 3000. I have used MEAN Stack. Also referring to some tutorials I developed a socket.io chat application running on port 3001.

How can I integrate/add this chat application to my MEAN Stack app. How to run two servers/ports at the same time?

socket.io

var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
nicknames = [];

server.listen(3001);

 app.get('/',function(req, res){
  res.sendfile(__dirname + '/index.html');
});

io.sockets.on('connection',function(socket){
socket.on('new user', function(data, callback){
    if (nicknames.indexOf(data) != -1){
        callback(false);
    }else {
        callback(true);
        socket.nickname = data;
        nicknames.push(socket.nickname);
        updateNicknames();
    }

});

function updateNicknames(){
    io.sockets.emit('usernames', nicknames);
}


socket.on('send message',function(data){
    io.sockets.emit('new message',{msg:data, nick:socket.nickname});

});

socket.on('disconnect',function(data){
    if(!socket.nickname) return;
    nicknames.splice(nicknames.indexOf(socket.nickname), 1);
    updateNicknames();
});

});

2
You can either just combine the two into the same process (just run both servers in the same node.js process) or you can run the socket.io application on the same port 3000 web server. Socket (and webSockets underneath it) are purposely designed so they can share a web server that is used for other types of web requests. - jfriend00
I tried to run both the applications on the same port, but only the first one is working. Other one shows that the port is already in use. How can I do this, where can I refer this? - Kabilesh
Rather than creating a new server for socket.io on the same port as your other server, you need to just pass it your other server and then socket.io will just share that server. - jfriend00

2 Answers

0
votes

you can create a global event and communicate between them. you can add the emit function to middlewere for express.

https://nodejs.org/api/events.html

0
votes

In case it's still relevant (I believe it is since I came here for the same reason) do this:

server.listen(app.get('port'), () => {
  console.log(`Socket is listening on port: ${app.get('port')}`);
});

P.S. This is in case you scaffolded the app with Express generator

Taken from here Github link