如何在运行python代码和nodejs之间进行通信

我想有一些Python代码正在运行,并与一个nodejs express服务器通信。 到目前为止,我可以通过以下两种机制之一让我的nodejs服务器调用python函数:产生一个python任务,或者让它与一个zerorpc python服务器通信。

首先,这个工作是有效的: http :

var express = require( "express" ); var http = require( "http" ); var app = express(); var server = http.createServer( app ).listen( 3000 ); var io = require( "socket.io" )( server ); app.use( express.static( "./public" ) ); io.on( "connection", function( socket ) { // Repeat interval is in milliseconds setInterval( function() { var spawn = require( 'child_process' ).spawn, py = spawn( 'python', [ 'mytime.py' ] ), message = ''; py.stdout.on( 'data', function( data ) { message += data.toString(); }); py.stdout.on( 'end', function() { socket.emit( "message", message ); }); }, 50 ); }); 

哪里mytime.py是

 from datetime import datetime import sys def main(): now = datetime.now() sys.stdout.write( now.strftime( "%-d %b %Y %H:%M:%S.%f" ) ) 

和zerorpc http://www.zerorpc.io/ ,如果这个Python代码正在运行:

 from datetime import datetime import sys import zerorpc class MyTime( object ): def gettime( self ): now = datetime.now() return now.strftime( "%-d %b %Y %H:%M:%S.%f" ) s = zerorpc.Server( MyTime() ) s.bind( "tcp://0.0.0.0:4242" ) s.run() 

这个nodejs代码的作品:

 var express = require( "express" ); var http = require( "http" ); var app = express(); var server = http.createServer( app ).listen( 3000 ); var io = require( "socket.io" )( server ); var zerorpc = require( "zerorpc" ); var client = new zerorpc.Client(); client.connect( "tcp://127.0.0.1:4242" ); app.use( express.static( "./public" ) ); io.on( "connection", function( socket ) { // Repeat interval is in milliseconds setInterval( function() { client.invoke( "gettime", function( error, res, more ) { socket.emit( "message", res.toString( 'utf8' ) ); } ); }, 50 ); }); 

但是我希望能够做的是,而不是仅仅调用python函数,我想要一个单独的python进程运行,并发送消息到nodejs服务器,它监听它们,然后处理它们。 我已经尝试了中间件socketio-wildcard,但是如果我尝试在nodejs express服务器的同一端口上设置一个带有zerorpc的python服务器,它会给出一个zmq.error.ZMQError:Address already in use error。

我知道我没有想到这个权利 – 我知道我错过了一些围绕进程间通信的逻辑,因为我的天真在这里 – 所以如果有一个更好的方法来执行从一个Python进程的消息发送与nodejs服务器聆听,我耳熟能详。

有任何想法吗?

提前谢谢了!

对于那些试图解决这个问题,这是一个解决scheme,谢谢Zeke Alexandre Nierenberg

对于node.js服务器代码:

 var express = require( "express" ); var app = express(); var http = require( "http" ); app.use( express.static( "./public" ) ); // where the web page code goes var http_server = http.createServer( app ).listen( 3000 ); var http_io = require( "socket.io" )( http_server ); http_io.on( "connection", function( httpsocket ) { httpsocket.on( 'python-message', function( fromPython ) { httpsocket.broadcast.emit( 'message', fromPython ); }); }); 

和发送消息的python代码:

 from datetime import datetime from socketIO_client import SocketIO, LoggingNamespace import sys while True: with SocketIO( 'localhost', 3000, LoggingNamespace ) as socketIO: now = datetime.now() socketIO.emit( 'python-message', now.strftime( "%-d %b %Y %H:%M:%S.%f" ) ) socketIO.wait( seconds=1 ) 

瞧!