【问题标题】:Listen to multiple ports at a time using Node.JS使用 Node.JS 一次监听多个端口
【发布时间】:2014-09-05 04:49:19
【问题描述】:

我只是想知道如何使用 Node.Js 一次监听多个端口。 目前,假设我有一个简单的聊天应用程序,它监听port no 8080 并将消息发送给通过该端口连接的每个人。但我想让它更像简单的实时聊天应用程序。如果有 10 个人,并且如果他们想向任何人发送消息,那么该消息应该只发送给那个特定的人,而不是其他人。 这是我的简单代码开始:

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

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    虽然技术上可行,但我会使用Socket.io 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
    });
    

    【讨论】:

      猜你喜欢
      • 2012-10-28
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 2012-08-24
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多