当前位置:   article > 正文

Python中使用websocket案例_python websocketapp

python websocketapp

1、安装websocket相关库

  1. pip install websocket
  2. pip install websocket-client

2、代码案例

  1. # coding=utf-8
  2. # 安装websocket相关库
  3. # pip install websocket
  4. # pip install websocket-client
  5. import json
  6. import websocket
  7. from threading import Thread
  8. import time
  9. def on_message(ws, message):
  10. print(message)
  11. def on_error(ws, error):
  12. print(error)
  13. def on_close(ws):
  14. print("### closed ###")
  15. def on_open(ws):
  16. def run(*args):
  17. for i in range(3):
  18. # send the message, then wait
  19. # so thread doesn't exit and socket
  20. # isn't closed
  21. data = {
  22. "namespace": "middleware-test",
  23. "container": "mysql",
  24. "clusterId": "default--test"
  25. }
  26. ws.send(json.dumps(data))
  27. time.sleep(1000)
  28. time.sleep(1)
  29. ws.close()
  30. print("Thread terminating...")
  31. Thread(target=run).start()
  32. if __name__ == "__main__":
  33. websocket.enableTrace(True)
  34. url = "ws://localhost:8080/terminal"
  35. ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close)
  36. ws.on_open = on_open
  37. ws.run_forever()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/150102
推荐阅读
相关标签
  

闽ICP备14008679号