0

看下面的例子:

var net = require('net');
var server = net.createServer(function(c) { //'connection' listener
  console.log('server connected');
  c.on('end', function() {
    console.log('server disconnected');
  });
  c.write('hello\r\n');
  c.pipe(c);
});
server.listen(8124, function() { //'listening' listener
  console.log('server bound');
});

我想有一种从createServer()函数外部访问 c.write 的方法

基本上我想做的是:

app.get('/msg/:theMsg', function (req, res) {
    res.setHeader('Content-Type', 'application/json');

server.c.write(req.params.theMsg, socketName); // i got socketName stored in an array

});
4

2 回答 2

1

与此类似,但是您将不得不做更多检查以查看套接字是否还活着,等等。

var net = require('net');
var sockets = {};
var server = net.createServer(function(c) { //'connection' listener
    var name = generate_name_from_con(c);
    console.log('server connected');
    sockets[name] = c;
    c.on('end', function() {
        delete sockets[n];
        console.log('server disconnected');
    });
    c.write('hello\r\n');
    c.pipe(c);
});
server.listen(8124, function() { //'listening' listener
    console.log('server bound');
});

app.get('/msg/:theMsg', function (req, res) {
    res.setHeader('Content-Type', 'application/json');

    if(socketName in sockets) sockets[socketName].write(req.params.theMsg);

});
于 2013-08-31T17:02:25.870 回答
0

只需将c对象作为参数传递给另一个函数:

var net = require('net');
var server = net.createServer(function(c) { //'connection' listener
   console.log('server connected');
   c.on('end', function() {
      console.log('server disconnected');
   });
   writestuff(c);
   c.pipe(c);
});
server.listen(8124, function() { //'listening' listener
   console.log('server bound');
});
function writestuff(c) {
   c.write('eueueueue');
}
于 2013-08-31T16:59:38.407 回答