I'm trying to implement simple data streamer in Python with sockets. Consider one server and one or more clients. I just want to read data from server, process it and send it to the client. Here's how I do it now:
outputsocket = socket.socket()
outputsocket.bind((self.outputaddress, self.outputport))
outputsocket.listen(2)
inputsocket = socket.socket()
rsocks, wsocks = [], []
rsocks.append(outputsocket)
rsocks.append(inputsocket)
recv_data = []
try:
inputsocket.connect((self.inputaddress, self.inputport))
while True:
try:
reads, writes, errs = select.select(rsocks, [], [])
except:
return
for sock in reads:
if sock == outputsocket:
client, address = sock.accept()
wsocks.append(client)
elif sock == inputsocket:
data_from_socket = sock.recv(8192)
if data_from_socket:
outdata = process_data(data_from_socket)
if wsocks:
reads, writes, errs = select.select([], wsocks, [], 0)
for sock in writes:
sock.send(outdata)
except KeyboardInterrupt:
inputsocket.close()
outputsocket.close()
# etc
Obviously, it's stripped down example, but I think you got the idea. Does anyone have better ideas?
inputsocket.close()
andoutputsocket.close()
in afinally:
block, instead of in the exception block, as a general clean up measure. – voithos Dec 22 '11 at 19:34