私は@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秒間待機し、接続と終了の間にこれらのステップの1つを実行する永遠のループを作成して、接続が開始時に1回だけ呼び出され、極端にすべてをシャットダウンする必要がある場合にのみ閉じるようにする必要があります。
スレッドを使用して、以前の作業が終わったら:
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
/programming/2846653/how-to-use-threading-in-python
/programming/510348/how-can-i-make-a-time-delay-in-python