简体   繁体   English

使用Node.JS一次监听多个端口

[英]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. 我只是想知道如何使用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. 目前,可以说我有一个简单的聊天应用程序,该应用程序侦听port no 8080 ,并将消息发送给通过该端口连接的每个人。 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. 如果有10个人,并且他们想向任何人发送消息,则该消息应仅发送给该特定人,而不发送给其他人。 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 . 我会使用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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM