javascript - Nodejs How to access a tcp socket outside the callback function -
if create server using code:
var net = require('net'); server = net.createserver(function(sock){ /** code here **/ }); server.listen(9000);
how access socket outside of callback function? me able create array/list of sockets can store , access whenever need send data specific client.
i did have weird workaround using don't think correct way. added socket server object saying:
this.socket = sock
inside callback function of createserver.
then can access saying server.socket useful if there 1 client.
to better understand trying accomplish have created class has constructor function holds code:
this.server = net.createserver(this.handleconnection)
this class has method handleconnection use callback. have method called start can called port parameter initiate server.listen(port).
what want accomplish method below:
sendcommand(message, socket){ socket.write(message); }
this way server can send message client function not within callback function of createserver. keep in mind doing within class using keyword within callback function accesses net server object , not class created.
every example see extremely simple tcp server has 1 message sent server within callback function. if shed light on problem great thanks!
i'm not sure if you're after, this.
var net = require('net'); var conns = []; var server = net.createserver(function(sock){ conns.push(sock); sock.on('close', function (){ // todo: remove conns }); }); server.listen(9000);
Comments
Post a Comment