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

相关推荐
kali-Myon几秒前
2025春秋杯网络安全联赛冬季赛-day3
python·安全·web安全·ai·php·web·ctf
AbsoluteLogic6 分钟前
Python——彻底明白Super() 该如何使用
python
小猪咪piggy9 分钟前
【Python】(4) 列表和元组
开发语言·python
墨理学AI27 分钟前
一文学会一点python数据分析-小白原地进阶(mysql 安装 - mysql - python 数据分析 - 学习阶段梳理)
python·mysql·数据分析
BLSxiaopanlaile32 分钟前
《凤凰架构-构建可靠的大型分布式系统》读书笔记 -关于网络通信安全性的一些总结
http·加密·认证授权·网络通信安全
数研小生34 分钟前
亚马逊商品列表API详解
前端·数据库·python·pandas
独好紫罗兰34 分钟前
对python的再认识-基于数据结构进行-a005-元组-CRUD
开发语言·数据结构·python
aesthetician36 分钟前
实时通信的艺术:Server-Sent Events (SSE) 与 WebSocket 的深度解析
网络·websocket·网络协议
jianghua0011 小时前
Python中的简单爬虫
爬虫·python·信息可视化
喵手1 小时前
Python爬虫实战:针对Python官网,精准提取出每一个历史版本的版本号、发布日期以及对应的文档/详情页链接等信息,并最终清洗为标准化的CSV文件!
爬虫·python·爬虫实战·零基础python爬虫教学·python官方数据采集·采集历史版本版本号等信息·导出csv文件