我想翻译一个用arduino制作的程序,在树莓皮上做同样的事情。在arduino中,我有一个带有javascript代码的网页作为web服务器,用来向程序代码发送get请求并告诉它我要做什么(例如,打开一个电磁阀)。为此,我必须让代码理解javascript代码从html网页发送的请求。在
这是网页上发送请求的javascript代码的一部分
function manual(X){
var request = new XMLHttpRequest();
request.open("GET", "/arduino/" + X + "&" + Math.random(), true);
request.send(null);
}
这是arduino程序中接收请求的部分
^{pr2}$
所以我想用python脚本和我在arduino中使用的同一个web页面执行相同的操作。我想我必须改变这一部分request.open("GET", "/arduino/" + X + "&" + Math.random(), true);
为了这个request.open("GET", "http://localhost:PORT" + X + "&" + Math.random(), true);
显然,将python脚本使用的端口“监听”传入的请求。在
事实上,我不知道该怎么做。我尝试过类似这样的套接字服务器代码import socket
import sys
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
s.close()
但什么也没发生。可能是这样的if request.method == 'GET' and 'q' in request.GET:
q = request.GET.get('q', None)
if q is not None:
这是一个在互联网上找到的代码,事实上出现在这个论坛上的一个问题上。在
我希望这个解释比以前更好。事实上,我想尝试从web服务器端捕获请求,并使用python脚本处理它们,就像我对arduino代码所做的那样。python脚本尚未编写,因为我必须解决这一点。其余的代码很容易翻译成python。在