简体   繁体   English

通过nodejs socket.io连接cmd线套接字服务器

[英]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. 我遇到的问题是,当我尝试启动与第3方cmd行可执行实例的单独套接字连接时,会作为套接字服务器运行。 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.io名称空间/房间类型,因此我了解到socket.io-events可能在以下方面有所帮助:

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); 对于这种通信,我假设我需要在端使用socket.io-client以便与cmd可执行文件对话,但是我在尝试执行socket2.use(router);时遇到异常socket2.use(router); where socket2 is my socket.io-client and router is the socket.io-events object. 其中socket2是我的socket.io-client ,路由器是socket.io-events对象。

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. 所有这些都在localhost上运行,到网页的节点是端口8001,到可执行文件的在端口8002上。请原谅代码,因为我一直在努力使它工作几天,现在有点难看了。

The cmd executable to execute and its arguments I have coming from the web page which works. 我要执行的cmd可执行文件及其参数来自有效的网页。 I am able to start the exe. 我能够启动exe。 The EXE expects a ACK on each message sent, thus why you see the code emitting it back. EXE期望在发送的每个消息上都有一个ACK,因此为什么您看到将代码发送回去的代码。

I have a interval where I set and update an element on the web page. 我有一个间隔来设置和更新网页上的元素。 I have another element that I set messages (msg). 我还有另一个设置消息(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. 在JGreenwell的帮助下,我能够解决我的问题。 I ended up having the node server communicate to the client html page via socket.io connection for messages. 我最终使节点服务器通过socket.io连接与客户端html页面通信以获取消息。 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. 节点服务器将启动cmd行可执行文件,为其提供要连接的端口,该端口与所使用的socket.io端口不同。

Once started, the executable would communicate with the server via the net module. 一旦启动,可执行文件将通过net模块与服务器通信。 The server would just pass the information on to the socket.io connection. 服务器只是将信息传递给socket.io连接。 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. html页面中的js知道如何解析消息以增加进度栏并在文本区域控件中列出消息。

I took it even further by having the messages be broadcast-ed to multiple clients on the socket.io connection. 我通过将消息广播到socket.io连接上的多个客户端来进一步扩展了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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