I want to send data from many clients to one stable client using Node.js

狂风中的少年 提交于 2020-01-14 06:03:28

问题


Here is my code:

var express = require('express');
var net = require('net');
var app = express();


//first of all connect to a stable client
var server = net.createServer(function(socket) {
// do nothing here . what i want is to use this socket in 
// (following) app.get() function
});
server.listen(1337, '127.0.0.1');

//receive request from other clients
app.get('/', function (req, res) 
{
// retriving mobileNumber and message
var mobileNumber = req.query.mobileNumber;
var message      = req.query.message;

//now i want to send this data to the stable client
// to which i have connected earlier.
res.end();
});

app.listen(6544);

I want to send data to the previously connected socket whenever a new '/' request arrives.


回答1:


One way to do that through one variable var sock as bellow.

var sock;
var server = net.createServer(function(socket) {
   sock = socket;
});
server.listen(1337, '127.0.0.1');

app.get('/', function (req, res) 
{
    if (sock) {
        // use sock here
    }
});


来源:https://stackoverflow.com/questions/35533118/i-want-to-send-data-from-many-clients-to-one-stable-client-using-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!