我正在尝试在PyQ5中使用QThread创建TCP线程。这是我的代码。我有3个线路来读取IP,端口和缓冲区大小。
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# vim:fileencoding=utf-8
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from TTP_Monitor_GUI import Ui_MainWindow
import socket
import sys
class WorkerObject(QObject):
@pyqtSlot(str, int, int)
def ListenTCP(self, TCP_IP, TCP_PORT,BUFFER_SIZE):
# create a socket object
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = (TCP_IP, TCP_PORT)
#print(server_address)
self.s.connect(server_address)
# Look for the response
while True:
self.data = self.s.recv(BUFFER_SIZE)
#amount_received += len(self.data)
print(self.data)
@pyqtSlot()
def StopTCP(self):
print("STOP_TCP")
print(self.data)
self.s.close()
print(self.data)
class Main(QMainWindow):
SignalTCPStart = pyqtSignal()
SignalTCPStop = pyqtSignal()
def __init__(self, parent=None):
super(QMainWindow, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.worker = WorkerObject()
self.thread = QThread()
self.worker.moveToThread(self.thread)
self.ui.btnConnect.clicked.connect(self.ConnectToTCP)
self.ui.btnDisconnect.clicked.connect(self.Disconnect)
def ConnectToTCP(self):
# set IP and Port
TCP_IP = self.ui.txtIP.text()
TCP_PORT = int(self.ui.txtPort.text())
BUFFER_SIZE = int(self.ui.txtBuffer.text())
self.SignalTCPStart.connect(self.worker.ListenTCP(TCP_IP, TCP_PORT,BUFFER_SIZE))
# No harm in calling thread.start() after the thread is already started.
self.thread.start()
self.SignalTCPStart.emit()
def Disconnect(self):
self.SignalTCPStop.connect(self.worker.StopTCP)
self.SignalTCPStop.emit()
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
myapp = Main()
myapp.show()
sys.exit(app.exec_())
我收到此错误:
Traceback (most recent call last):
File "C:\Software\TTP_Monitor\TTP_Monitor.py", line 65, in ConnectToTCP
self.SignalTCPStart.connect(self.worker.ListenTCP(TCP_IP, TCP_PORT,BUFFER_SIZE))
TypeError: argument 1 has unexpected type 'NoneType'
有趣的是,没有UI和QThread,while循环完美无缺。我可以读取数据,但上面的代码会出现此错误。
期待您的回复。