我试图在node.js应用程序和python之间使用socket.io与python端的socketIO-client 0.5.1库进行通信。以下是两个代码块:
var http = require('http').createServer();
http.listen(6000);
var io = require('socket.io').listen(http, { log: false });
var events = require('events');
var eventEmitter = new events.EventEmitter();
var counter = 0;
io.sockets.on('connection', function (socket) {
eventEmitter.on('observe', function(message){
socket.emit('sendVoltage', {});
});
socket.on('voltage', function (data) {
console.log(counter + " - " + data.voltage);
if (counter++ < 500) {
eventEmitter.emit('observe', '');
}
});
eventEmitter.emit('observe', '');
});
#!/usr/bin/python
import time, signal, sys
from Adafruit_ADS1x15 import ADS1x15
from socketIO_client import SocketIO
ADS1115 = 0x01 # 16-bit ADC
adc = ADS1x15(ic=ADS1115)
socketIO = SocketIO('chair01', 6000)
def on_voltage_response(*args):
print 'on_voltage_response', args
def on_sendVoltage(*args):
voltage = adc.readADCSingleEnded(0, 4096, 250) / 1000
print "Emitting voltage"
socketIO.emit('voltage', {'voltage': voltage}, on_voltage_response)
socketIO.wait_for_callbacks(seconds=1)
print "Voltage emitted"
socketIO.on('sendVoltage', on_sendVoltage)
socketIO.wait(seconds=1)
当检测到sendVoltage
消息时,执行on_sendVoltage
功能,发出电压消息,但不会从发送返回控制。下一条消息进来,下一条消息从未返回。在某些时候,它会因过多的递归调用而死亡。
我做错了什么?
答案 0 :(得分:0)
您正在on_sendVoltage函数中调用socketIO.wait_for_callbacks()。你的主要应该是这样的:
state = 'waiting'
while state == 'waiting':
self.socket.wait(seconds=1)
这将使Python继续等待,但你的回调仍将继续运行。如果要执行其他操作,可以更改回调中的状态。