【问题标题】:nodejs socket receive data from one port and make available on another portnodejs套接字从一个端口接收数据并在另一个端口上可用
【发布时间】:2017-05-28 07:56:58
【问题描述】:

我有两个设备。一台设备将数据发送到一个套接字端口,即。 9000 和其他设备连接到另一个端口,即。 8000 并且我希望第二个设备接收与从第一个设备在端口 9000 上接收到的相同数据。

我想使用nodejs和socket io制作一个脚本来接收来自一个端口的数据,例如:192.168.25.42:9000,并且相同的接收数据应该在不同的端口192.168.25.42:8000上可用

任何帮助表示赞赏。

【问题讨论】:

  • 为什么不能使用同一个端口?请您提供一些背景信息。以便我们更好地了解您的需求。
  • 我想,当 9000 端口接收到任何数据时,该数据应该立即在 8000 端口上可用。设备已经构建,我们无法更改它们的逻辑。不能使用相同的端口。
  • 所以要明确一点:9000 端口上的 socket.io 服务器从客户端接收数据,你想将该数据推送到连接到 8000 端口的客户端吗?
  • 是的,完全正确。知道怎么做吗?
  • 我看到你很少接受答案,人们会花时间帮助你,但你在帮助你的时候却没有礼貌的评论。

标签: node.js socket.io port


【解决方案1】:

你需要有 2 个 socket.io 服务器,一个监听 9000 端口,另一个监听 8000 端口。

当一台服务器接收到数据时,您将该数据发送给另一台服务器。

const express = require("express");
const http = require('http');

const app8000 = express();
const app9000 = express();

const server8000 = http.Server(app8000);
const server9000 = http.Server(app9000);

const io8000 = require('socket.io')(server8000);
const io9000 = require('socket.io')(server9000);

server8000.listen(8000);
server9000.listen(9000);

// Server on port 8000

io8000.on('connection', socket => {
    socket.on('my-event', data => {
        //Push data to clients connected to server on port 9000
        io9000.emit("event-from-8000", "From 8000: " + data);
    });
});

// Server on port 9000

io9000.on('connection', socket => {
    socket.on('my-event', data => {
        //Push data to clients connected to server on port 8000
        io8000.emit("event-from-9000", "From 9000: " + data);
    });
});

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2019-08-31
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多