python中websockets与主线程传递参数

目录

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

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

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

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

服务端:web_server.py

python 复制代码
import asyncio
import json
import base64
import queue
import threading
import time
import cv2
import moment
import numpy as np
import requests
import websockets


class WebServer:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.msg_queue = queue.Queue()
        self.clients = []
        self.flag = True

    async def echo(self, websocket, path):
        client_ip, client_port = websocket.remote_address
        self.clients.append(websocket)
        while True:
            try:
                # 在这里处理收到的消息
                # async for recv_text in websocket:
                recv_text = await websocket.recv()
                with open("aa.txt","w") as f:
                    f.write(recv_text)
                data = json.loads(recv_text)
                #if type(data) is not dict: # 判断数据
                #    continue
                self.msg_queue.put(res)
 
            except websockets.ConnectionClosed:
                print("ConnectionClosed...", websocket.remote_address)  # 链接断开
                self.clients.remove(websocket)
                break
            except websockets.InvalidState:
                print("InvalidState...", websocket.remote_address)  # 无效状态
                self.clients.remove(websocket)
                break
            except Exception as err:
                print("ws:", err)
                pass

    def connect(self):
        asyncio.set_event_loop(asyncio.new_event_loop())
        start_server = websockets.serve(self.echo, self.host, self.port)
        asyncio.get_event_loop().run_until_complete(start_server)
        asyncio.get_event_loop().run_forever()
        print("连接成功!")

    def run(self):
        t = threading.Thread(target=self.connect)
        t.start()
        print("已启动!")

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

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

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

python 复制代码
from web_server import WebServer


class MainThread:
    def __init__(self):
        self.ws = WebServer("192.168.6.28", 8000)
        self.ws.run()

    def run(self):
        while True:
            try:
                data = self.ws.msg_queue.get()
                # flag = data.get("flag")  # 内容标签 判断是否是自己想要的内容
                # if not flag:
                #    continue
                try:
                    # 处理数据
                    print(data)
                    pass
                except Exception as e:
                    print("报错:", e)
            except Exception as err:
                print("报错:", err)
                pass


if __name__ == '__main__':
    M = MainThread()
    M.run()

客户端:web_client.py

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

python 复制代码
import json

import websocket


class WebClient:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.conn = None
        self.flag = False

    def connect(self):
        try:
            url = f"ws://{self.host}:{self.port}"
            self.conn = websocket.create_connection(url)
            self.flag = True
        except Exception as err:
            self.flag = False

    def close(self):
        self.conn.close()

    def recv(self):
        data = self.conn.recv(1024)
        print(data)

    def send(self, data):
        self.conn.send(data)


if __name__ == '__main__':
    host = "192.168.6.28"
    # host = "127.0.0.1"
    port = 8000
    ws = WebClient(host, port)
    if not ws.flag:
        ws.connect()
    with open("bb.txt") as f:
        data = f.read()
    ws.send(data)
相关推荐
J不A秃V头A2 分钟前
Redisson 中开启看门狗(watchdog)机制
java·分布式锁·看门狗
草字5 分钟前
uniapp input限制输入负数,以及保留小数点两位.
java·前端·uni-app
李迟5 分钟前
某Linux发行版本无法使用nodejs程序重命名文件问题的研究
java·linux·服务器
封步宇AIGC7 分钟前
量化交易系统开发-实时行情自动化交易-4.2.3.指数移动平均线实现
人工智能·python·机器学习·数据挖掘
互联网杂货铺8 分钟前
自动化测试基础知识总结
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
MapleLea1f18 分钟前
26届JAVA 学习日记——Day14
java·开发语言·学习·tcp/ip·程序人生·学习方法
小汤猿人类18 分钟前
SpringTask
开发语言·python
没有黑科技24 分钟前
基于web的音乐网站(Java+SpringBoot+Mysql)
java·前端·spring boot
爪哇学长25 分钟前
解锁API的无限潜力:RESTful、SOAP、GraphQL和Webhooks的应用前景
java·开发语言·后端·restful·graphql
老赵的博客33 分钟前
QT 自定义界面布局要诀
开发语言·qt