run_forever()
ユーザーの (メイン) スレッドがメソッド呼び出しでブロックされないように、マルチスレッド Web ソケット クライアント クラスを作成しました。コードは正常に動作しているように見えますが、最終的にスレッドを停止すると、Web ソケットがきれいに閉じられず、プロセスが終了しません。私はkill -9
それを取り除くために毎回しなければなりません。スレッドのメソッドを呼び出してjoin()
、子スレッドの実行が完了するまでメインスレッドが待機するようにしましたが、役に立ちませんでした。
コードは以下のようになります。スレッドの終了/停止を適切に行うのを手伝ってもらえますか?
import thread
import threading
import time
import websocket
class WebSocketClient(threading.Thread):
def __init__(self, url):
self.url = url
threading.Thread.__init__(self)
def run(self):
# Running the run_forever() in a seperate thread.
#websocket.enableTrace(True)
self.ws = websocket.WebSocketApp(self.url,
on_message = self.on_message,
on_error = self.on_error,
on_close = self.on_close)
self.ws.on_open = self.on_open
self.ws.run_forever()
def send(self, data):
# Wait till websocket is connected.
while not self.ws.sock.connected:
time.sleep(0.25)
print 'Sending data...', data
self.ws.send("Hello %s" % data)
def stop(self):
print 'Stopping the websocket...'
self.ws.keep_running = False
def on_message(self, ws, message):
print 'Received data...', message
def on_error(self, ws, error):
print 'Received error...'
print error
def on_close(self, ws):
print 'Closed the connection...'
def on_open(self, ws):
print 'Opened the connection...'
if __name__ == "__main__":
wsCli = WebSocketClient("ws://localhost:8888/ws")
wsCli.start()
wsCli.send('Hello')
time.sleep(.1)
wsCli.send('World')
time.sleep(1)
wsCli.stop()
#wsCli.join()
print 'After closing client...'