我正在尝试使用PyQt5.QtNetwork.QTcpSocket和PyQt5.QtNetwork.QTcpServer作为基础来实现自定义的TCP和服务器。文档声明必须重写QTcpServer.incomingConnection才能返回自定义套接字对象。这在原则上似乎很好,但我总是在一些奇怪的行为上犹豫不决。在调用QTcpServer.nextPendingConnection时,该方法似乎确实返回了预期的MyNewSocket实例,但是,当一个人访问新套接字的任何属性或方法时,解释器首先返回said属性/方法,然后再通知您,到目前为止我还没有找到合理的解释的AttributeError: 'NoneType' object has no attribute 'anyAttribute'。这里是一个MWE,它显示了这种行为。我使用的是PyQt5版本5.15。
tcpmodule.py
from PyQt5.QtNetwork import QTcpSockert, QTcpServer
class MyNewSocket(QTcpSocket):
"""do some additional stuff to the
original QTcpSocket stuff"""
pass
class MyNewServer(QTcpServer):
def incomingConnection(self, handle):
"""Returns a MyNewSocket instance instead of
original QTcpSocket instance"""
socket = MyNewSocket(self)
socket.setSocketDescriptor(handle)
self.addPendingConnection(socket)
self.newConnection.emit()server.py
from tcpmodule import MyNewServer
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtNetwork import QHostAddress
app = QApplication([])
win = QMainWindow()
server = MyNewServer(win)
server.listen(QHostAddress.SpecialAddress.LocalHost, 9999)
def newConnection():
socket = server.nextPendingConnection()
print("Acces any Attribute ", socket.connected)
print("Socket is ", socket, " Socket Type is", type(socket))
server.newConnection.connect(newConnection)
win.show()
app.exec()client.py
#!/usr/bin/env python3
from tcpmodule import MyNewSocket
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtNetwork import QHostAddress
app = QApplication([])
win = QMainWindow()
socket = MyNewSocket(win)
socket.connectToHost(QHostAddress.SpecialAddress.LocalHost, 9999)
def connected():
socket.write(b"Hello, World!")
socket.connected.connect(connected)
win.show()
app.exec()在运行server.py和后续的client.py连接之后,我得到以下输出
Acces any Attribute <bound PYQT_SIGNAL connected of MyNewSocket object at 0x7f4be28597e0>
Socket is <tcpmodule.MyNewSocket object at 0x7f4be28597e0> Socket Type is <class 'tcpmodule.MyNewSocket'>
Traceback (most recent call last):
File "./server.py", line 13, in newConnection
print("Acces any Attribute ", socket.connected)
AttributeError: 'NoneType' object has no attribute 'connected' 有人能告诉我发生了什么事吗?!
发布于 2022-07-30 21:58:19
根据文档,incomingConnection()似乎发出了newConnection()信号,但实际上没有。
通过查看资料来源,我们看到它只是创建了套接字,设置了它的描述符并将其附加到挂起的连接中:
void QTcpServer::incomingConnection(qintptr socketDescriptor)
{
#if defined (QTCPSERVER_DEBUG)
qDebug("QTcpServer::incomingConnection(%i)", socketDescriptor);
#endif
QTcpSocket *socket = new QTcpSocket(this);
socket->setSocketDescriptor(socketDescriptor);
addPendingConnection(socket);
}实际上,信号只由私有函数readNotification()发出,该函数调用incomingConnection()并最终发出信号。
因此,您不必自己发出它,因为在第二次调用nextPendingConnection()时,您将得到一个nullptr (None),因为之前的调用已经读取了套接字,并且没有更多可用的连接。
https://stackoverflow.com/questions/73178486
复制相似问题