0

This is my first time programming in Python and needs help with using websocket. I'm using the example from here as the example. The project I'm working requires that I send update to the server constantly with the connection open. I'd used the extension for firefox to connect to the websocket and knows that it works and I can send data to it. However, I'm using having problem with modifying the code in main to keep the connection open so that I can keep sending data. The on_open runs only once at connection open

    import websocket
try:
    import thread
except ImportError:
    import _thread as 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://echo.websocket.org/",
                              on_open = on_open,
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)

    ws.run_forever()
3
  • You're closing the web socket as soon as you write 3 items. Commented Mar 11, 2021 at 23:06
  • This is from the sample code from the websocket-client example. I'm looking to modify this sample so that I can keep the connection open until I'm done with sending data which could be 10 send to 10000. I can use the on_open to send the initial config and then return to the main to continue sending my data. Commented Mar 12, 2021 at 14:20
  • I'm able to make it work. I used the create_connection instead and just have it loop after the connection to send data. Commented Mar 12, 2021 at 16:21

1 Answer 1

2
ws= websocket.create_connection(ws_url)

ws.send(init_data) # send the initial data
while True:
   # get the data to send
   data = process_data(get_data())
   if not data:
      break
   
   try:
      ws.send(json.dumps(data))
   except Exception as e:
      print(e)
      break
   finally:
      ws.close()
Sign up to request clarification or add additional context in comments.

1 Comment

How'd you get the process_data function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.