简体   繁体   中英

Listen to multiple ports at a time using Node.JS

I am just wondering that how would I able to listen to multiple ports at a time using Node.Js. Currently, lets say I have a simple chat application that listen to port no 8080 and send the message to everyone that is connected through that port. But i want to make it more like simple real time chat application. If there are 10 people and if they want to send a message to any one then that message should only go to that particular person not other persons. Here is simple code of mine to start:

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

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


http.listen(3000, function(){
  console.log('listening on *:3000');
});

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
     io.emit('chat message', msg);
  });
});

any help will be appreciated.

Rather than using multiple ports, while technically possible, I would use Socket.io Rooms . You can then send messages to just people in those rooms.

io.on('connection', function (socket) {
   socket.join('some room'); //join room

   io.to('some room').emit('some event'); //send messages to members of room
});

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