Python client keeps websocket open and reacts to received messages
multithreading, python, websocket
Solution
I finished with this code, doing what I'm expecting. Git it from here
import websocket
import thread
import time
def on_message(ws, message):
print message
def on_error(ws, error):
print error
def on_close(ws):
print "### closed ###"
def on_open(ws):
def run(*args):
for i in range(3):
time.sleep(1)
ws.send("Hello %d" % i)
time.sleep(1)
ws.close()
print "thread terminating..."
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:5000/chat",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
Problem
I'm trying to implement a REST client in python that reacts to messages received from the server received through an opened websocket with the concerned server. Here is the scenario: - client opens a websocket with the server - from time to time, the server sends a message to the client - when the client receives the messages, it gets some information from the server The current client I have is able to open the websocket and to receive the message from the server. However, as soon as it receives the messages, it gets the information from the server then terminates while I'd like to keep it listening for other messages that will make it get a new content from the server. Here is the piece of code I have: ``` def openWs(serverIp, serverPort): ##ws url setting wsUrl = "ws://"+serverIp+":"+serverPort+"/websocket" ##open ws ws = create_connection(wsUrl) ##send user id print "Sending User ID..." ws.send("user_1") print "Sent" ##receiving data on ws print "Receiving..." result = ws.recv() ##getting new content getUrl = "http://"+serverIp+":"+serverPort+"/"+result+"/entries" getRest(getUrl) ``` I don't know if using threads is appropriate or not, I'm not expert in that. If someone could help, it'll be great. Thanks in advance.