Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python client keeps websocket open and reacts to received messages

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.

like image 484
radar Avatar asked Jan 18 '26 15:01

radar


1 Answers

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()
like image 59
radar Avatar answered Jan 20 '26 05:01

radar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!