我想翻译一个用arduino制作的程序在树莓派上做同样的事情。在arduino中,我有一个网页,其中包含一些javascript代码作为Web服务器,以向程序代码发送get请求并告诉它我想要做什么(例如,打开电磁阀)。为此,我必须使代码理解来自html网页的javascript代码发送的请求。
这是网页上用于发送请求的javascript代码的一部分;
<script type="text/javascript">
function manual(X){
var request = new XMLHttpRequest();
request.open("GET", "/arduino/" + X + "&" + Math.random(), true);
request.send(null);
}
</script>
这是收到请求的arduino程序的一部分;
YunClient client = server.accept(); // try to get client
if (client) { // got client?
String req = client.readString();
req.trim();
Console.println(req);
所以我想用python脚本和我在arduino中使用的相同网页做同样的事情。我想我必须改变这一部分;
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。