当前位置:   article > 正文

python中websockets与主线程传递参数

python中websockets与主线程传递参数

目录

一、子线程创建websockets服务端接收客户端数据

二、主线程内启动子线程接收并处理数据

一、子线程创建websockets服务端接收客户端数据并存入队列

发送的消息客户端与服务端统一,多种消息加入判断的标签

服务端:web_server.py

  1. import asyncio
  2. import json
  3. import base64
  4. import queue
  5. import threading
  6. import time
  7. import cv2
  8. import moment
  9. import numpy as np
  10. import requests
  11. import websockets
  12. class WebServer:
  13. def __init__(self, host, port):
  14. self.host = host
  15. self.port = port
  16. self.msg_queue = queue.Queue()
  17. self.clients = []
  18. self.flag = True
  19. async def echo(self, websocket, path):
  20. client_ip, client_port = websocket.remote_address
  21. self.clients.append(websocket)
  22. while True:
  23. try:
  24. # 在这里处理收到的消息
  25. # async for recv_text in websocket:
  26. recv_text = await websocket.recv()
  27. with open("aa.txt","w") as f:
  28. f.write(recv_text)
  29. data = json.loads(recv_text)
  30. #if type(data) is not dict: # 判断数据
  31. # continue
  32. self.msg_queue.put(res)
  33. except websockets.ConnectionClosed:
  34. print("ConnectionClosed...", websocket.remote_address) # 链接断开
  35. self.clients.remove(websocket)
  36. break
  37. except websockets.InvalidState:
  38. print("InvalidState...", websocket.remote_address) # 无效状态
  39. self.clients.remove(websocket)
  40. break
  41. except Exception as err:
  42. print("ws:", err)
  43. pass
  44. def connect(self):
  45. asyncio.set_event_loop(asyncio.new_event_loop())
  46. start_server = websockets.serve(self.echo, self.host, self.port)
  47. asyncio.get_event_loop().run_until_complete(start_server)
  48. asyncio.get_event_loop().run_forever()
  49. print("连接成功!")
  50. def run(self):
  51. t = threading.Thread(target=self.connect)
  52. t.start()
  53. print("已启动!")

二、主线程内启动子线程接收并处理数据

收到消息后根据情况处理消息

主线程调用服务端:main.py

  1. from web_server import WebServer
  2. class MainThread:
  3. def __init__(self):
  4. self.ws = WebServer("192.168.6.28", 8000)
  5. self.ws.run()
  6. def run(self):
  7. while True:
  8. try:
  9. data = self.ws.msg_queue.get()
  10. # flag = data.get("flag") # 内容标签 判断是否是自己想要的内容
  11. # if not flag:
  12. # continue
  13. try:
  14. # 处理数据
  15. print(data)
  16. pass
  17. except Exception as e:
  18. print("报错:", e)
  19. except Exception as err:
  20. print("报错:", err)
  21. pass
  22. if __name__ == '__main__':
  23. M = MainThread()
  24. M.run()

客户端:web_client.py

客户端连接服务端,并发送消息

  1. import json
  2. import websocket
  3. class WebClient:
  4. def __init__(self, host, port):
  5. self.host = host
  6. self.port = port
  7. self.conn = None
  8. self.flag = False
  9. def connect(self):
  10. try:
  11. url = f"ws://{self.host}:{self.port}"
  12. self.conn = websocket.create_connection(url)
  13. self.flag = True
  14. except Exception as err:
  15. self.flag = False
  16. def close(self):
  17. self.conn.close()
  18. def recv(self):
  19. data = self.conn.recv(1024)
  20. print(data)
  21. def send(self, data):
  22. self.conn.send(data)
  23. if __name__ == '__main__':
  24. host = "192.168.6.28"
  25. # host = "127.0.0.1"
  26. port = 8000
  27. ws = WebClient(host, port)
  28. if not ws.flag:
  29. ws.connect()
  30. with open("bb.txt") as f:
  31. data = f.read()
  32. ws.send(data)

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

闽ICP备14008679号