Python QtNetwork.QTcpSocket.readAll() 和 QtNetwork.QTcpSocket.write() 不起作用
Posted
技术标签:
【中文标题】Python QtNetwork.QTcpSocket.readAll() 和 QtNetwork.QTcpSocket.write() 不起作用【英文标题】:Python QtNetwork.QTcpSocket.readAll() and QtNetwork.QTcpSocket.write() not working 【发布时间】:2018-11-20 11:45:15 【问题描述】:我正在做一个简单的套接字连接,而 read.All() 和 write() 并没有给我任何回报。
import PySide.QtNetwork as Network
import PySide.QtCore as Core
proxyAddress = '127.0.0.1'
proxyPort = 1025
tcpSocket = Network.QTcpSocket()
tcpSocket.connectToHost(proxyAddress, proxyPort)
tcpSocket.state() 给出
"PySide.QtNetwork.QAbstractSocket.SocketState.ConnectingState"
当我尝试发送一些东西时,我得到了这个:
tcpSocket.write("Hello")
5L
对于 readAll():
tcpSocket.readAll()
PySide.QtCore.QByteArray('')
哦,我尝试断开连接:
tcpSocket.disconnectFromHost()
它会返回下一行来写,就好像它成功断开连接但是当我检查状态时:
tcpSocket.state()
"PySide.QtNetwork.QAbstractSocket.SocketState.ConnectingState"
感谢任何帮助。
【问题讨论】:
【参考方案1】:首先,信号状态为ConnectingState
,表示尚未建立连接,因此此时执行任何任务都不正确,您必须等待状态为ConnectedState
。另一方面,您指出的端口可能正在被另一个应用程序使用,因为它通常是为另一个任务保留的一个小数字。在下一部分中,我将展示一个服务器和客户端的示例(首先启动服务器,然后您可以启动所需数量的客户端。)。最后,在 Qt 中,任务不应该同步执行,而是通过信号执行,因为 Qt 事件循环需要更新内部和外部变量状态。
server.py
import uuid
from PySide import QtCore, QtNetwork
class ServerManager(QtCore.QObject):
def __init__(self, parent=None):
super(ServerManager, self).__init__(parent)
self._server = QtNetwork.QTcpServer(self)
self._server.newConnection.connect(self.on_newConnection)
self._clients =
def launch(self, address=QtNetwork.QHostAddress.Any, port=9999):
return self._server.listen(QtNetwork.QHostAddress(address), port)
@QtCore.Slot()
def on_newConnection(self):
socket = self._server.nextPendingConnection()
socket.readyRead.connect(self.on_readyRead)
if socket not in self._clients:
self._clients[socket] = uuid.uuid4()
@QtCore.Slot()
def on_readyRead(self):
socket = self.sender()
resp = socket.readAll()
code = self._clients[socket]
print("From[]- message: ".format(code, resp))
socket.write("Server: " + str(resp)[::-1])
if __name__ == '__main__':
import sys
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QtCore.QCoreApplication(sys.argv)
address = '127.0.0.1'
port = 9000
server = ServerManager()
if not server.launch(address, port):
sys.exit(-1)
sys.exit(app.exec_())
client.py
from PySide import QtCore, QtNetwork
class ClientManager(QtCore.QObject):
def __init__(self, parent=None):
super(ClientManager, self).__init__(parent)
self._socket = QtNetwork.QTcpSocket(self)
self._socket.stateChanged.connect(self.on_stateChanged)
self._socket.readyRead.connect(self.on_readyRead)
self._timer = QtCore.QTimer(self, interval=1000)
self._timer.timeout.connect(self.sendMessage)
def launch(self, address=QtNetwork.QHostAddress.Any, port=9999):
return self._socket.connectToHost(QtNetwork.QHostAddress(address), port)
@QtCore.Slot(QtNetwork.QAbstractSocket.SocketState)
def on_stateChanged(self, state):
if state == QtNetwork.QAbstractSocket.ConnectedState:
self._timer.start()
print("connected")
elif state == QtNetwork.QAbstractSocket.UnconnectedState:
print("disconnected")
QtCore.QCoreApplication.quit()
@QtCore.Slot()
def sendMessage(self):
if self._socket.state() == QtNetwork.QAbstractSocket.ConnectedState:
msg = QtCore.QDateTime.currentDateTime().toString()
self._socket.write(msg)
@QtCore.Slot()
def on_readyRead(self):
print("Response: ", self._socket.readAll())
if __name__ == '__main__':
import sys
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QtCore.QCoreApplication(sys.argv)
address = '127.0.0.1'
port = 9000
server = ClientManager()
server.launch(address, port)
sys.exit(app.exec_())
【讨论】:
感谢您的评论。运行 connectToHost() 后我应该等待多长时间才能最终连接?它处于 ConnectingState 有一段时间了。 @mikanim 这取决于许多变量,例如网络、硬件等,因此没有答案。正确的做法是使用我在示例中显示的信号。以上是关于Python QtNetwork.QTcpSocket.readAll() 和 QtNetwork.QTcpSocket.write() 不起作用的主要内容,如果未能解决你的问题,请参考以下文章