nodejs套接字从一个端口接收数据并在另一个端口上可用 [英] nodejs socket receive data from one port and make available on another port
问题描述
我有两个设备.一台设备将数据发送到一个套接字端口,即. 9000和另一个设备连接到另一个端口,即8000,并且我希望第二台设备接收从第一台设备在端口9000上接收到的相同数据.
I have two devices. One devices send data to one socket port ie. 9000 and another devices connected to another port ie. 8000 and I want 2nd device receive same data that is received on port 9000 from first device.
我想制作一个脚本,使用nodejs和socket io从一个端口接收数据,例如:192.168.25.42:9000
,并且相同的接收数据应该在不同的端口192.168.25.42:8000
上可用
I want to make a script using nodejs and socket io to receive data from one port like: 192.168.25.42:9000
and same received data should be available on different port 192.168.25.42:8000
任何帮助表示赞赏.
推荐答案
您将需要拥有2台socket.io服务器,其中一台侦听端口9000,另一台侦听端口8000.
You'll need to have 2 socket.io servers, one listening on port 9000 and the other one listening on port 8000.
一台服务器接收数据时,会将数据发送给另一台服务器.
When one server receives data, you emit that data to the other one.
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);
});
});
这篇关于nodejs套接字从一个端口接收数据并在另一个端口上可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!