简体   繁体   中英

Node net.createServer(), sending data back to the client oustside of on( 'data' ) callback

So I have a little server going in Electron, using net and with this class:

var net = require('net')

class Server {

    constructor(port) {

        this.Port = port

        var HOST = '127.0.0.1'  // todo: get ip from host name

        this.Server = net.createServer();
        this.Server.listen(port, HOST);

        this.Server.on('connection',  (sock) => {

            console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);

            sock.on('data', function (data) {
                console.log( `client sent data ${data}`)
                sock.write( `Server sends back ${data} to client`)
            });

            sock.on('close', function (data) {
                let index = sockets.findIndex(function (o) {
                    return o.remoteAddress === sock.remoteAddress && o.remotePort === sock.remotePort;
                })
                console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
            });
        });

    } // constructor

}

and I call it thus:

var server = new Server( 3000 )

testing it with telnet localhost 3000 . And it all works dandy but it's kind of tied into a question and answer thing, only sending a response to the client when it's received data from the client in io('data'). Is there any way to send data from, say, outside the class, in a more arbitrary way. As in, for example:

var server = new Server( 3000 )
this.Server.write( data )

This seems to work:

in the this.Server.on('connection') in the constructor:

this.Socket = sock

add the method:

Send( msg ) {
    if ( !this.Socket ) {
        console.log( "Server.Send(): no client connected" )
    }
    this.Socket.write( msg )
}

and in sock.on( 'close' ) set the socket method back to null:

this.Socket = null

then:

var server = new Server( 3000 )
server.Send( data )

(needs a check for a connection)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM