PyQt5 編寫一個UDP Server

Tarzen發表於2024-09-09

main.py

import socket
import sys
import time

from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtCore import QThread, pyqtSignal
from view.udpserver import Ui_Form


class UDPServer(QThread):
    message = pyqtSignal(str)  # 主要是將接受到的資訊,返給主執行緒

    def __init__(self):
        super().__init__()
        self.udp_runing = True

    def run(self):
        # 啟動udpserver
        print('執行了 run方法')
        self.udp_socker = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udp_socker.bind(('0.0.0.0', 12345))
        while self.udp_runing:
            try:
                data, addr = self.udp_socker.recvfrom(1024)
                message = f"接收到:{addr}:{data.decode('utf-8')}"
                self.udp_socker.sendto(b'Received:%s' % data, addr)
                self.message.emit(message)
            except Exception as e:
                print(e)

    def stop(self):
        self.udp_runing = False
        self.udp_socker.close()
        self.quit()
        self.wait()


class MyWin(QWidget, Ui_Form):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.udp_thread = None
        # 放到最後:防止其他屬性尚未載入
        self.iniUI()

    def iniUI(self):
        self.resize(500, 500)
        self.pushButton.clicked.connect(self.start_udp)
        self.pushButton_2.clicked.connect(self.stop_udp)
        if self.udp_thread is None or not self.udp_thread.udp_runing:
            self.start_udp_button(1)

    def start_udp(self):
        if self.udp_thread is None or not self.udp_thread.udp_runing:
            self.textEdit.setText('正在啟動')
            self.udp_thread = UDPServer()  # 子執行緒一定要加self
            self.udp_thread.message.connect(self.show_message)
            self.udp_thread.start()
            self.start_udp_button(statr=2)
            time.sleep(2)
            self.start_udp_button(statr=0)
            self.textEdit.setText('啟動成功')

    def stop_udp(self):
        if self.udp_thread.udp_runing:
            self.textEdit.setText('正在關閉udp')
            self.udp_thread.stop()
            self.start_udp_button(statr=2)
            time.sleep(2)
            self.start_udp_button(statr=1)
            self.textEdit.setText('已經關閉')

    def show_message(self, mes):
        self.textEdit.setText(mes)

    def start_udp_button(self, statr=None):
        if statr == 0:
            # 啟動upd,
            self.pushButton.setEnabled(False)
            self.pushButton_2.setEnabled(True)
        elif statr == 1:
            # 關閉後的狀態
            self.pushButton.setEnabled(True)
            self.pushButton_2.setEnabled(False)
        elif statr == 2:
            # 狀態切換狀態
            self.pushButton.setEnabled(False)
            self.pushButton_2.setEnabled(False)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MyWin()
    w.show()
    app.exec_()


view.udpserver中的Ui_Form.py 該檔案是將ui檔案轉換成py檔案

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'udpserver.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(486, 401)
        self.layoutWidget = QtWidgets.QWidget(Form)
        self.layoutWidget.setGeometry(QtCore.QRect(90, 80, 331, 41))
        self.layoutWidget.setObjectName("layoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.pushButton_2 = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout.addWidget(self.pushButton_2)
        self.textEdit = QtWidgets.QTextEdit(Form)
        self.textEdit.setGeometry(QtCore.QRect(150, 190, 241, 91))
        self.textEdit.setObjectName("textEdit")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "啟動UDP"))
        self.pushButton_2.setText(_translate("Form", "關閉UDP"))

相關文章