Python创建多个线程分别启动http、WebSocket服务

我的计划是启动主程序后新建3个独立的线程,一个线程执行PLC读取,一个线程启动工艺测试(含http服务),另外一个线程启动WebSocket。

新增 /lib/PlcReader.py

python 复制代码
# 执行 PLC 读取类
# 读取 PLC 配置文件
# 定时(每秒)读取PLC值,发送到内存模块中,并通过 WebSocket 发送给所有连接客户端

import time

class PlcReader(object):
    def __init__(self, job_name):
        self.jobName = job_name
        self.readPlcValueConfigList = []

    def run(self):
        print("PLC读取模块启动")
        self.read_config()
        # 定时读取 PLC 的值
        while True:
            self.read_plc_value()
            time.sleep(1)

    def read_config(self):
        print("读取 PLC 配置文件")
        self.readPlcValueConfigList = [{"name": "aaa"}]

    def refresh_config(self):
        print("更新 PLC 配置文件")
        self.readPlcValueConfigList = []

    def read_plc_value(self):
        print("读取 PLC 值")
        # 如有没有读取配置列表,则不读取
        if not self.readPlcValueConfigList or len(self.readPlcValueConfigList) == 0:
            print("如有没有读取配置列表")
            return
        print("去更新内存中的PLC值,并通过WebSocket发送给所有连接客户端")

新增/lib/ProcessTester.py

python 复制代码
# 工艺测试主程序
# 提供初始化工艺
# 提供开始执行
# 提供暂定执行
# 提供结束执行(紧急停止可调用)
# 提供手动调节
# 对外提供 http 调用服务,通过 http 调用来执行工艺的测试过程(初始化工艺、开始执行、暂停执行、结束执行、手动调节)

import http.server
import socketserver
class HTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        message = "Hello, World!"
        self.wfile.write(bytes(message, "utf8"))
        return

    def do_POST(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        message = "Hello, World2!"
        self.wfile.write(bytes(message, "utf8"))
        return

class ProcessTester:
    def __init__(self, port):
        self.handler = HTTPRequestHandler
        self.port = port

    def start(self):
        with socketserver.TCPServer(("", self.port), self.handler) as httpd:
            print("HTTP 服务启动在端口", self.port)
            httpd.serve_forever()

/lib/WebSocketServer.py

python 复制代码
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.websocket

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print('WebSocket opened')

    def on_message(self, message):
        print('WebSocket message received {}'.format(message))
        self.write_message(message)

    def on_close(self):
        print('WebSocket closed')

    def check_origin(self, origin):
        return True

class WebSocketServer:
    def __init__(self, port):
        self.port = port
    def start(self):
        application = tornado.web.Application([(r'/websocket', WebSocketHandler)])
        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(self.port)
        tornado.ioloop.IOLoop.instance().start()

最外层新增Main.py

python 复制代码
# 启动三个线程
# 1. PLC读取模块
# 2. 执行工艺试验模块
# 3. WebSocket通讯模块


import threading
import time

from lib.PlcReader import PlcReader
from lib.ProcessTester import ProcessTester
from lib.WebSocketServer import WebSocketServer


plcReader = PlcReader("PlcReader")
processTester = ProcessTester(8080)
wsServer = WebSocketServer(9001)

if __name__ == "__main__":
    print("启动程序")

    # 创建线程对象
    thread1 = threading.Thread(target=plcReader.run)
    thread2 = threading.Thread(target=processTester.start)
    thread3 = threading.Thread(target=wsServer.start)

    # 启动线程
    thread1.start()
    thread2.start()
    thread3.start()

    time.sleep(10)
    plcReader.refresh_config()
    print("aaa")

编辑完了之后,启动Main.py

相关推荐
卷Java10 小时前
上下文压缩
开发语言·windows·python
AI技术增长10 小时前
Pytorch图像去噪实战(十二):DDPM图像去噪完整训练流程,构建可复现扩散模型工程
pytorch·python·深度学习
本地化文档10 小时前
setuptools-docs-l10n
python·github·gitcode
梦想不只是梦与想11 小时前
Python 属性访问的 MRO 规则
python·mro规则
Ulyanov11 小时前
基于 Python 的三维动态导弹攻防演示系统设计与实现:从架构到实战的深度剖析
开发语言·python·qt·架构·雷达电子对抗
Leinwin11 小时前
Claude 四月宕机七次:从一次事故看企业级 AI 部署的容灾设计
后端·python·flask
棉猴11 小时前
Python海龟绘图之绘制文本
javascript·python·html·write·turtle·海龟绘图·输出文本
渣渣盟11 小时前
大数据技术栈全景图:从零到一的入门路线(深度实战版)
大数据·hadoop·python·flink·spark
码农阿豪11 小时前
Python 操作金仓数据库的完全指南(上篇):连接管理与高可用
开发语言·数据库·python
eqwaak011 小时前
4月30号(科技信息差)
python·科技·信息可视化·数据挖掘·数据分析