查看以下示例:
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()
函数
基本上我想做的是:
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
});
答案 0 :(得分: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);
});
答案 1 :(得分: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');
}