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

相关推荐
流烟默17 分钟前
基于Optuna 贝叶斯优化的自动化XGBoost 超参数调优器
人工智能·python·机器学习·超参数优化
海琴烟Sunshine19 分钟前
leetcode 263. 丑数 python
python·算法·leetcode
AI视觉网奇38 分钟前
yolo 获取异常样本 yolo 异常
开发语言·python·yolo
程序员爱钓鱼1 小时前
Python编程实战 面向对象与进阶语法 迭代器与生成器
后端·python·ipython
程序员爱钓鱼1 小时前
Python编程实战 面向对象与进阶语法 JSON数据读写
后端·python·ipython
TH88861 小时前
一体化负氧离子监测站:实时、精准监测空气中负氧离子浓度及其他环境参数
python
檐下翻书1731 小时前
Spring Boot 深度剖析:从虚拟线程到声明式 HTTP 客户端,再到云原生最优解
spring boot·http·云原生
苏打水com2 小时前
0基础学前端:100天拿offer实战课(第3天)—— CSS基础美化:给网页“精装修”的5大核心技巧
人工智能·python·tensorflow
顾安r2 小时前
11.5 脚本 本地网站收藏(解封归来)
linux·服务器·c语言·python·bash
Blossom.1182 小时前
把AI“贴”进路灯柱:1KB决策树让老旧路灯自己报「灯头松动」
java·人工智能·python·深度学习·算法·决策树·机器学习