2
我有一個連續輸出數據的設備,我想將數據發送到同一網絡上的客戶端,因爲它產生了,我找不到一個好的解決方案。這是我正在嘗試的。通過網絡使用python流式傳輸連續數據
服務器:
import SocketServer
from subprocess import Popen,PIPE
class Handler(SocketServer.BaseRequestHandler):
def handle(self):
if not hasattr(self, 'Proc'):
self.Proc = Popen('r.sh', stdout=PIPE)
socket = self.request[1]
socket.sendto(self.Proc.stdout.readline(),self.client_address)
if __name__ == "__main__":
HOST, PORT = "192.168.1.1", 6001
server = SocketServer.UDPServer((HOST, PORT), Handler)
server.serve_forever()
客戶:
import socket
data = " ".join(sys.argv[1:])
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(data + "\n", ("192.168.1.1", 6001))
try:
received = sock.recv(1024)
while True:
print "Sent: {}".format(data)
print "Received: {}".format(received)
sock.sendto('more' + "\n", ("192.168.1.1", 6001))
received = sock.recv(1024)
except:
print "No more messages"
ARG [1]爲客戶端是輸出數據的行幾分鐘,我需要,因爲它被創建處理的程序。問題似乎是,每次客戶端發送另一個請求時,都會創建一個新的Handler對象,所以我鬆散了Proc。我怎樣才能流Proc.stdout?
編輯:該設備是一個Korebot2,所以我由於空間有限的訪問其他python庫。