pyqt5 多线程 tcpip server newConnection槽函数不触发

以下是有问题的代码

from PyQt5.QtCore import QThread, pyqtSignal, QByteArray
from PyQt5.QtNetwork import QTcpServer, QHostAddress
import numpy as np
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *



class TcpThread(QThread):

    # connected = pyqtSignal(str)

    def __init__(self, parent=None):
        print("init")
        super(TcpThread, self).__init__(parent)


        self.timer = QTimer(self)
        self.timer.timeout.connect(self.timerFunction)


    def connectedSlot(self):
        print("服务器建立连接")
        self.socket = self.tcpServer.nextPendingConnection()
        # self.timer.start(100)

    def connectErrorSlot(self):
        print("服务器出错")

    def timerFunction(self):
        print("timer")
        if not hasattr(self.timerFunction, 'x'):  # hasattr函数的第一个变量为当前函数名,第二个为变量名,加单引号
            self.timerFunction.x = 0
        a = np.sin(np.pi / 50 * self.timerFunction.x) * 1300
        self.timerFunction.x += 1
        self.socket.write(a)

    def run(self):
        print("发送数据多线程启动")
        self.tcpServer = QTcpServer()
        self.tcpServer.setObjectName("server")
        self.tcpServer.newConnection.connect(self.connectedSlot)
        self.tcpServer.acceptError.connect(self.connectErrorSlot)
        self.tcpServer.listen(QHostAddress("127.0.0.1"), 9407)

原先的代码,tcpserver初始化在多线程的run函数里面,这样绑定的槽函数就不会触发

from PyQt5.QtCore import QThread, pyqtSignal, QByteArray
from PyQt5.QtNetwork import QTcpServer, QHostAddress
import numpy as np
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *



class TcpThread(QThread):

    # connected = pyqtSignal(str)

    def __init__(self, parent=None):
        print("init")
        super(TcpThread, self).__init__(parent)
        self.tcpServer = QTcpServer()
        self.tcpServer.setObjectName("server")
        self.tcpServer.newConnection.connect(self.connectedSlot)
        self.tcpServer.acceptError.connect(self.connectErrorSlot)
        self.tcpServer.listen(QHostAddress("127.0.0.1"), 9407)

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.timerFunction)


    def connectedSlot(self):
        print("服务器建立连接")
        self.socket = self.tcpServer.nextPendingConnection()
        # self.timer.start(100)

    def connectErrorSlot(self):
        print("服务器出错")

    def timerFunction(self):
        print("timer")
        if not hasattr(self.timerFunction, 'x'):  # hasattr函数的第一个变量为当前函数名,第二个为变量名,加单引号
            self.timerFunction.x = 0
        a = np.sin(np.pi / 50 * self.timerFunction.x) * 1300
        self.timerFunction.x += 1
        self.socket.write(a)

    def run(self):
        print("发送数据多线程启动")


        # self.timer.start(100)

现在的代码,tcpserver初始化放在类的构造函数中,这样绑定的槽函数才能触发,原因我没想通,如果有知道的请留言给我,共同学习进步

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值