【python】UI/ function code seperated(ISP), multithread TCP server receive multi client and send to specific one client
少少行數實現的python tcp-server,自愉自樂用 :)
This example mention on:
- ISP:pyqt5 Ui_form class and function code in different class
- Use ThreadingTcpServer class not QTcpSocket class
(if you don’t need Graphic interface, this example can actually remove QT libraries) - Send by independent thread, received in ThreadingTcpServer handle
- cross-threading communication use Queue
Graphic user interface
explain each thread 類別介紹
main thread of this application
class TcpServer_Tool(QWidget, Ui_Form):
tcp-server thread
class client_handler(BaseRequestHandler):
thread to watch number of connected clients
class check_socket_sum(threading.Thread):
thread to send message to one client by IP
class client_sendBack(threading.Thread):
explain each queue 事件隊列
client_msg_queue = queue.Queue()
client_add_addr_queue = queue.Queue()
client_remove_addr_queue = queue.Queue()
client_recv_queue =queue.Queue()
client_send_msg_queue = queue.Queue()
client_socket_list = []
如下:
name | description |
---|---|
client_msg_queue | for client connect/ disconnect action signal |
client_add_addr_queue/ client_remove_addr | for user interface to add client list |
client_recv_queue | content received from client |
client_send_msg_queue | user send to specific clients from server |
源碼
tcpserver_tool.py
Graphic User interface:
(translated from PyQt5 .ui file format)
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'tcpServer_tool.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(1078, 728)
font = QtGui.QFont()
font.setFamily("Century Gothic")
font.setPointSize(11)
Form.setFont(font)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setObjectName("gridLayout")
self.groupBox = QtWidgets.QGroupBox(Form)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(2)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setObjectName("groupBox")
self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout_2.setObjectName("gridLayout_2")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setObjectName("label")
self.gridLayout_2.addWidget(self.label, 0, 0, 1, 1)
self.s1_line_1 = QtWidgets.QLineEdit(self.groupBox)
self.s1_line_1.setObjectName("s1_line_1")