私はライブラジオストリーマーを構築していますが、どうやって複数の接続を処理するべきか不思議でした。今私の経験から選択すると、オーディオがストリーミングされるのがブロックされます。 3秒間しか再生せず、再生を停止します。私が意味するものの例を提供します。私は選択やスレッディングを使うべきかアドバイスが必要ですか?
import socket, select
headers = """
HTTP/1.0 200 OK\n
Content-Type: audio/mpeg\n
Connection: keep-alive\n
\n\n
"""
file="/path/to/file.mp3"
bufsize=4096 # actually have no idea what this should be but python-shout uses this amount
sock = socket.socket()
cons = list()
buf = 0
nbuf = 0
def runMe():
cons.append(sock)
file = open(file)
nbuf = file.read(bufsize) # current buffer
while True:
buf = nbuf
nbuf = file.read(bufsize)
if len(buf) == 0:
break
rl, wl, xl = select.select(cons, [], [], 0.2)
for s in rl:
if s == sock:
con, addr = s.accept()
con.setblocking(0)
cons.append(con)
con.send(header)
else:
data = s.recv(1024)
if not data:
s.close()
cons.remove(s)
else:
s.send(buf)
これはselectを使用する方法の例です。しかし、その歌はずっと再生されません。しかし、私がselectループの外に送ると、それは再生されますが、それは2番目の接続で死ぬでしょう。スレッディングを使うべきですか?
あなたは_output_アベイラビリティも制御したいですか? 'socket.send'もあなたのコードをブロックする可能性のある操作です – user3159253
また、これは完全な実例かもしれません。 – user3159253
スレッドと選択は2つの非常に異なるものです。ほとんどの場合、両方を使用する必要があります。あるいは、ねじれたようなフレームワークを使用しています(他にもうまくいきます)。 –