对于@Chris Stratton 所指的保持活动的 TCP 连接,我找到了一个很好的基本解决方案:
import socket
# Set up a TCP/IP socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# Connect as client to a selected server
# on a specified port
s.connect(("url_to_device_n",80))
# Protocol exchange - sends and receives
s.send("GET /answer_json HTTP/1.0\n\n")
while True:
resp = s.recv(1024)
if resp == "": break
print resp, # here instead of print parse json
# Close the connection when completed
s.close()
print "\ndone"
您应该创建一个等待 0.1 秒的永恒循环,然后在 connect 和 close 之间执行这些步骤之一,以便仅在启动时调用一次连接,并且仅在极端需要关闭所有内容时才关闭。
使用线程,一旦以前的工作:
import urllib2
from multiprocessing.dummy import Pool as ThreadPool
import socket
import time
def sendData( urlToDevice ):
# Set up a TCP/IP socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("url_to_device_n",80))
while True:
time.sleep(0.1)
# Protocol exchange - sends and receives
s.send("GET /answer_json HTTP/1.0\n\n")
while True:
resp = s.recv(1024)
if resp == "": break
print resp, # here instead of print parse json
# Close the connection when completed
s.close()
print "\ndone"
#########################
# This is main program: #
#########################
urls = [
'url_to_device_1',
'url_to_device_2',
'url_to_device_3',
'..',
'url_to_device_n',
]
# make the Pool of workers
pool = ThreadPool(n)
# open the urls in their own threads
results = pool.map(sendData, urls)
# close the pool and wait for the work to finish
pool.close()
pool.join()
资料来源:
http://www.wellho.net/resources/ex.php4?item=y303/browser.py
https://stackoverflow.com/questions/2846653/how-to-use-threading-in-python
https://stackoverflow.com/questions/510348/how-can-i-make-a-time-delay-in-python