简体   繁体   中英

connect cmd line socket server via nodejs socket.io

I have a server communicating to a client web page, sending it message. This is working great based on the many tutorials and searching stack overflow :)

Where I am having an issue is when I attempt to startup a separate socket connection to a 3rd party cmd line executable instance runs as a socket server. The 3rd party executable does not adhere to the socket.io namespace/room type of events, so I read that socket.io-events may help where instead of:

socket.on('some key', function(){/**do stuff*/}); I could:
eventRouter.on('*', function(){/*do stuff*/});

For this communication, I am assuming I need to use socket.io-client on the side in order to talk to the cmd executable, but I am getting exceptions trying to do a socket2.use(router); where socket2 is my socket.io-client and router is the socket.io-events object.

All runs on localhost, node to web page is port 8001 and to executable is on port 8002. Please pardon the code, for I have been trying to get this to work for a few days and is a bit ugly now.

The cmd executable to execute and its arguments I have coming from the web page which works. I am able to start the exe. The EXE expects a ACK on each message sent, thus why you see the code emitting it back.

I have a interval where I set and update an element on the web page. I have another element that I set messages (msg).

var http = require('http');
var url = require('url');
var fs = require('fs');
var server;

server = http.createServer(function(req, res){
// your normal server code
var path = url.parse(req.url).pathname;
switch (path){
    case '/':
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write('<h1>Hello! Try the <a href="/test.html">Test page</a>    </h1>');
        res.end();
        break;
        case '/socket.html':
            fs.readFile(__dirname + path, function(err, data){
                if (err){
                    return send404(res);
                }
                res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'});
                res.write(data, 'utf8');
                res.end();
            });
            break;
            default: send404(res);
        }
    }),

    send404 = function(res){
        res.writeHead(404);
        res.write('404');
        res.end();
    };

    server.listen(8001);
    var str = "ack0";
    var bytes = [];

    for (var i = 0; i < str.length; ++i) {
        bytes.push(str.charCodeAt(i));
    }

    // use socket.io
    var io = require('socket.io').listen(server);
    // define interactions with client
    io.sockets.on('connection', function(socket){
        //send data to client
        setInterval(function(){
            socket.emit('date', {'date': new Date()});
        }, 1000);

        //recieve client data
        socket.on('client_data', function(data){

        var spawn = require('child_process').spawn;
        console.log('pre-spawned');
        spawn(data.cmd, data.args, {});

        setTimeout(function() {
            console.log('hello world!');
        }, 1000);
        var aptIO = require('socket.io-client');
        var router = require('socket.io-events')();
        var socket2 = aptIO.connect('localhost:8002', {reconnect: true});

        router.on('connection', function(s){
            //send data to client
            console.log('apt');

            router.on('*', function(sock, args, next){
                var name = args.shift(), msg = args.shift();
                console.log(name + " " + JSON.stringify(msg));
                sock.emit(bytes);
                io.sockets.emit('msg', {'msg': JSON.stringify(msg)})
                next();
            });
            s.emit(bytes);

        });
        console.log('spawned');

        // getting runtime exceptions here...have tried various things...
        socket2.use(router);
    });

});

With the help from JGreenwell, I was able to resolve me issue. I ended up having the node server communicate to the client html page via socket.io connection for messages. The node server would launch the cmd line executable providing it the port to connect to which is different from the socket.io port used.

Once started, the executable would communicate with the server via the net module. The server would just pass the information on to the socket.io connection. the js in the html page knows how to parse the message in order to increment the progress bar and list the messages in a text area control.

I took it even further by having the messages be broadcast-ed to multiple clients on the socket.io 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