python中websockets與主線程傳遞參數(shù)的實現(xiàn)
一、子線程創(chuàng)建websockets服務(wù)端接收客戶端數(shù)據(jù)并存入隊列
發(fā)送的消息客戶端與服務(wù)端統(tǒng)一,多種消息加入判斷的標(biāo)簽
服務(wù)端:web_server.py
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: # 判斷數(shù)據(jù)
# 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) # 無效狀態(tài)
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("已啟動!")二、主線程內(nèi)啟動子線程接收并處理數(shù)據(jù)
收到消息后根據(jù)情況處理消息
主線程調(diào)用服務(wù)端:main.py
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") # 內(nèi)容標(biāo)簽 判斷是否是自己想要的內(nèi)容
# if not flag:
# continue
try:
# 處理數(shù)據(jù)
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
客戶端連接服務(wù)端,并發(fā)送消息
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)到此這篇關(guān)于python中websockets與主線程傳遞參數(shù)的實現(xiàn)的文章就介紹到這了,更多相關(guān)python websockets與主線程傳遞參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python中虛擬環(huán)境使用總結(jié)和完整詳細(xì)示例
Python虛擬環(huán)境是管理項目依賴的重要工具,能夠有效避免不同項目間的依賴沖突,本文為大家整理了Python虛擬環(huán)境的使用總結(jié)和完整詳細(xì)示例,希望對大家有所幫助2025-06-06
PyTorch學(xué)習(xí)之軟件準(zhǔn)備與基本操作總結(jié)
這篇文章主要介紹了PyTorch學(xué)習(xí)之軟件準(zhǔn)備與基本操作總結(jié),文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)python的小伙伴們有很好地幫助,需要的朋友可以參考下2021-05-05
TensorFlow高效讀取數(shù)據(jù)的方法示例
這篇文章主要介紹了TensorFlow高效讀取數(shù)據(jù)的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
Python中的分支與循環(huán)結(jié)構(gòu)解讀
這篇文章主要介紹了Python中的分支與循環(huán)結(jié)構(gòu)解讀,在Python編程中,分支(Branch)和循環(huán)(Loop)是掌握的關(guān)鍵要素之一,它們允許您根據(jù)條件執(zhí)行不同的代碼塊,以及重復(fù)執(zhí)行特定任務(wù),需要的朋友可以參考下2023-10-10
圖文詳解在Anaconda安裝Pytorch的詳細(xì)步驟
Anaconda指的是一個開源的Python發(fā)行版本,其包含了conda、Python等180多個科學(xué)包及其依賴項,下面這篇文章主要給大家介紹了關(guān)于在Anaconda安裝Pytorch的詳細(xì)步驟,需要的朋友可以參考下2022-07-07
APIStar:一個專為Python3設(shè)計的API框架
今天小編就為大家分享一篇關(guān)于一個專為Python3設(shè)計的API框架:APIStar,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-09-09

