主程序
"""
声明:
"""
from PyQt5 import QtCore, QtWidgets ,QtGui
from PyQt5.QtWidgets import QApplication,QItemDelegate,QAbstractItemView
from too_ui import Ui_MainWindow
import sys
from socket import *
import socket
import threading
import time
import datetime
class EmptyDelegate(QItemDelegate):
"""项目委托列不可编辑"""
def __init__(self,parent):
super(EmptyDelegate, self).__init__(parent)
def createEditor(self, QWidget, QStyleOptionViewItem, QModelIndex):
""" 项目委托列不可编辑 """
return None
class MainWindow_main_1(QtWidgets.QMainWindow,Ui_MainWindow):
""" 加载UI文件 """
textEdit_append = QtCore.pyqtSignal(str)
QtCore_checkbox = QtCore.pyqtSignal(list)
def __init__(self):
super(MainWindow_main_1, self).__init__()
self.setupUi(self)
self.initUI()
hostname = socket.gethostname()
serverIP = socket.gethostbyname(hostname)
self.lineEdit.setText(serverIP)
self.address = self.lineEdit.text()
self.lineEdit_2.setText('8888')
self.port = int(self.lineEdit_2.text())
self.buffsize = 99999
self.conn_list = []
self.conn_dt = {}
self.ui_checkbox_list = []
self.sk_on_off = False
def initUI(self):
""" 事件绑定 """
self.textEdit_append.connect(self.write_msg_TCP)
self.QtCore_checkbox.connect(self.set_QtCore_checkbox)
self.pushButton.clicked.connect(lambda:self.thread_it(self.sk_run))
self.pushButton_2.clicked.connect(lambda:self.thread_it(self.send))
self.pushButton_4.clicked.connect(lambda:self.thread_it(self.send_2))
self.tableWidget.setItemDelegateForColumn(0, EmptyDelegate(self))
self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
self.tableWidget.horizontalHeader().setStretchLastSection(True)
self.tableWidget.setColumnWidth(0, 50)
self.tableWidget.setColumnWidth(1, 150)
@staticmethod
def checkbox_Checked():
"""checkbox 选中 居中显示"""
checkbox1 = QtWidgets.QCheckBox()
checkbox1.setCheckState(QtCore.Qt.Checked)
hLayout = QtWidgets.QHBoxLayout()
hLayout.addWidget(checkbox1)
hLayout.setAlignment(checkbox1, QtCore.Qt.AlignCenter)
widget = QtWidgets.QWidget()
widget.setLayout(hLayout)
return widget, checkbox1
def set_QtCore_checkbox(self,conn_list):
self.tableWidget.setRowCount(len(self.conn_list))
self.tableWidget.setColumnCount(2)
self.ui_checkbox_list.clear()
for x in range(len(conn_list)):
self.tableWidget.setRowHeight(x, 40)
widget1, checkbox1 = self.checkbox_Checked()
self.tableWidget.setCellWidget(x, 0, widget1)
self.tableWidget.setItem(x, 1, QtWidgets.QTableWidgetItem(str(conn_list[x])))
self.ui_checkbox_list.append(checkbox1)
@staticmethod
def thread_it(func, *args):
'''将函数打包进线程'''
t = threading.Thread(target=func, args=args)
t.setDaemon(True)
t.start()
def write_msg_TCP(self, msg):
self.plainTextEdit.appendPlainText(msg)
self.plainTextEdit.moveCursor(QtGui.QTextCursor.End)
self.plainTextEdit.document().setMaximumBlockCount(1000)
def now_time(self):
""" 获取当前的时间毫秒级 """
return_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
return return_time+" "
def tcplink(self,sock, addr):
"""接收数据"""
try:
while self.sk_on_off:
recvdata = sock.recv(self.buffsize).decode('utf-8')
if recvdata:
self.textEdit_append.emit("%s来源于:%s 接收数据:\n%s\n\n" % (self.now_time(),addr, recvdata))
if not recvdata:
self.textEdit_append.emit('%s 断开连接了,offline %s' % (self.now_time(),str(addr)))
_index = self.conn_list.index(addr)
self.conn_dt.pop(addr)
self.conn_list.pop(_index)
self.tableWidget.removeRow(int(_index))
self.QtCore_checkbox.emit(self.conn_list)
sock.close()
break
except:
sock.close()
def recs(self):
try:
if not self.sk_on_off:
self.pushButton.setText('创建中请稍等...')
time.sleep(3)
self.sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sk.bind((self.address, self.port))
self.sk.listen(100)
self.pushButton.setText('创建成功,断开连接')
self.sk_on_off = True
self.ui_checkbox_list.clear()
while self.sk_on_off:
client_sock, client_address = self.sk.accept()
if client_address not in self.conn_list:
self.conn_list.append(client_address)
self.conn_dt[client_address] = client_sock
self.QtCore_checkbox.emit(self.conn_list)
self.textEdit_append.emit(('新客户端连接 connect from:%s\n' % str(client_address)))
t = threading.Thread(target=self.tcplink, args=(client_sock, client_address))
t.start()
else:
self.sk_on_off = False
self.pushButton.setText('开始创建')
for x in self.conn_list:
self.conn_dt[x].close()
self.conn_list.clear()
self.conn_dt.clear()
self.sk.close()
except Exception as e:
try:
self.sk_on_off = False
self.pushButton.setText('开始创建')
for x in self.conn_list:
self.conn_dt[x].close()
self.conn_list.clear()
self.conn_dt.clear()
self.sk.close()
except:
pass
print('异常了%s'% e)
finally:
thread_num = len(threading.enumerate())
print("主线程:线程数量是%d \n" % thread_num)
def send(self):
"""发送数据 """
if self.sk_on_off:
for i in range(len(self.ui_checkbox_list)):
if self.ui_checkbox_list[i].isChecked():
print('选择的第几个客户端:',i,self.tableWidget.item(i,1).text())
data1 = self.plainTextEdit_2.toPlainText()
if self.conn_dt[self.conn_list[i]]:
self.conn_dt[self.conn_list[i]].sendall(data1.encode('utf-8'))
else:
self.textEdit_append.emit('未连接!!!\n')
def send_2(self):
"""发送数据 """
if self.sk_on_off:
for i in range(len(self.ui_checkbox_list)):
if self.ui_checkbox_list[i].isChecked():
print('选择的第几个客户端:',i,self.tableWidget.item(i,1).text())
data2 = self.plainTextEdit_3.toPlainText()
if self.conn_dt[self.conn_list[i]]:
self.conn_dt[self.conn_list[i]].sendall(data2.encode('utf-8'))
else:
self.textEdit_append.emit('未连接!!!\n')
def sk_run(self):
t2 = threading.Thread(target=self.recs, args=(), name='recs')
t2.start()
if __name__ == '__main__':
app =QApplication(sys.argv)
window = MainWindow_main_1()
window.show()
sys.exit(app.exec_())
**
ui 文件 too_ui .py
**
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1033, 594)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_6 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_6.setContentsMargins(6, 6, 6, 6)
self.gridLayout_6.setObjectName("gridLayout_6")
self.splitter_2 = QtWidgets.QSplitter(self.centralwidget)
self.splitter_2.setOrientation(QtCore.Qt.Horizontal)
self.splitter_2.setObjectName("splitter_2")
self.widget = QtWidgets.QWidget(self.splitter_2)
self.widget.setMaximumSize(QtCore.QSize(250, 16777215))
self.widget.setObjectName("widget")
self.gridLayout_4 = QtWidgets.QGridLayout(self.widget)
self.gridLayout_4.setContentsMargins(0, 0, 0, 0)
self.gridLayout_4.setHorizontalSpacing(0)
self.gridLayout_4.setObjectName("gridLayout_4")
self.label = QtWidgets.QLabel(self.widget)
self.label.setObjectName("label")
self.gridLayout_4.addWidget(self.label, 0, 1, 1, 1)
self.lineEdit = QtWidgets.QLineEdit(self.widget)
self.lineEdit.setObjectName("lineEdit")
self.gridLayout_4.addWidget(self.lineEdit, 0, 2, 1, 1)
self.label_2 = QtWidgets.QLabel(self.widget)
self.label_2.setObjectName("label_2")
self.gridLayout_4.addWidget(self.label_2, 1, 1, 1, 1)
self.lineEdit_2 = QtWidgets.QLineEdit(self.widget)
self.lineEdit_2.setObjectName("lineEdit_2")
self.gridLayout_4.addWidget(self.lineEdit_2, 1, 2, 1, 1)
self.groupBox_3 = QtWidgets.QGroupBox(self.widget)
self.groupBox_3.setTitle("")
self.groupBox_3.setObjectName("groupBox_3")
self.gridLayout = QtWidgets.QGridLayout(self.groupBox_3)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setSpacing(0)
self.gridLayout.setObjectName("gridLayout")
self.tableWidget = QtWidgets.QTableWidget(self.groupBox_3)
self.tableWidget.setRowCount(0)
self.tableWidget.setColumnCount(2)
self.tableWidget.setObjectName("tableWidget")
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
self.gridLayout.addWidget(self.tableWidget, 0, 1, 1, 1)
self.gridLayout_4.addWidget(self.groupBox_3, 3, 0, 1, 3)
self.pushButton = QtWidgets.QPushButton(self.widget)
self.pushButton.setMinimumSize(QtCore.QSize(0, 30))
self.pushButton.setObjectName("pushButton")
self.gridLayout_4.addWidget(self.pushButton, 2, 1, 1, 2)
self.widget_2 = QtWidgets.QWidget(self.splitter_2)
self.widget_2.setObjectName("widget_2")
self.gridLayout_5 = QtWidgets.QGridLayout(self.widget_2)
self.gridLayout_5.setContentsMargins(0, 0, 0, 0)
self.gridLayout_5.setHorizontalSpacing(0)
self.gridLayout_5.setObjectName("gridLayout_5")
self.splitter = QtWidgets.QSplitter(self.widget_2)
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setObjectName("splitter")
self.groupBox_2 = QtWidgets.QGroupBox(self.splitter)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(8)
sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().hasHeightForWidth())
self.groupBox_2.setSizePolicy(sizePolicy)
self.groupBox_2.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.groupBox_2.setObjectName("groupBox_2")
self.gridLayout_3 = QtWidgets.QGridLayout(self.groupBox_2)
self.gridLayout_3.setContentsMargins(0, -1, 0, 0)
self.gridLayout_3.setHorizontalSpacing(0)
self.gridLayout_3.setVerticalSpacing(6)
self.gridLayout_3.setObjectName("gridLayout_3")
self.pushButton_4 = QtWidgets.QPushButton(self.groupBox_2)
self.pushButton_4.setMinimumSize(QtCore.QSize(0, 30))
self.pushButton_4.setObjectName("pushButton_4")
self.gridLayout_3.addWidget(self.pushButton_4, 1, 1, 1, 1)
self.plainTextEdit_2 = QtWidgets.QPlainTextEdit(self.groupBox_2)
self.plainTextEdit_2.setObjectName("plainTextEdit_2")
self.gridLayout_3.addWidget(self.plainTextEdit_2, 0, 0, 1, 1)
self.pushButton_2 = QtWidgets.QPushButton(self.groupBox_2)
self.pushButton_2.setMinimumSize(QtCore.QSize(0, 30))
self.pushButton_2.setObjectName("pushButton_2")
self.gridLayout_3.addWidget(self.pushButton_2, 0, 1, 1, 1)
self.plainTextEdit_3 = QtWidgets.QPlainTextEdit(self.groupBox_2)
self.plainTextEdit_3.setObjectName("plainTextEdit_3")
self.gridLayout_3.addWidget(self.plainTextEdit_3, 1, 0, 1, 1)
self.groupBox = QtWidgets.QGroupBox(self.splitter)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(55)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setBaseSize(QtCore.QSize(0, 0))
self.groupBox.setObjectName("groupBox")
self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
self.gridLayout_2.setHorizontalSpacing(0)
self.gridLayout_2.setObjectName("gridLayout_2")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_2.addItem(spacerItem, 0, 0, 1, 1)
self.pushButton_3 = QtWidgets.QPushButton(self.groupBox)
self.pushButton_3.setMaximumSize(QtCore.QSize(100, 16777215))
self.pushButton_3.setObjectName("pushButton_3")
self.gridLayout_2.addWidget(self.pushButton_3, 0, 1, 1, 1)
self.plainTextEdit = QtWidgets.QPlainTextEdit(self.groupBox)
self.plainTextEdit.setObjectName("plainTextEdit")
self.gridLayout_2.addWidget(self.plainTextEdit, 1, 0, 1, 2)
self.gridLayout_5.addWidget(self.splitter, 0, 0, 1, 1)
self.gridLayout_6.addWidget(self.splitter_2, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
self.pushButton_3.clicked.connect(self.plainTextEdit.clear)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "服务器"))
self.label.setText(_translate("MainWindow", "服务器IP:"))
self.label_2.setText(_translate("MainWindow", "服务器端口:"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "选择"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "在线客户端"))
self.pushButton.setText(_translate("MainWindow", "开始创建"))
self.groupBox_2.setTitle(_translate("MainWindow", "发送数据"))
self.pushButton_4.setText(_translate("MainWindow", "2发送数据"))
self.pushButton_2.setText(_translate("MainWindow", "1发送数据"))
self.groupBox.setTitle(_translate("MainWindow", "接收数据"))
self.pushButton_3.setText(_translate("MainWindow", "清除数据"))
|