gpt4 book ai didi

python - QTcpSocket read 未发出

转载 作者:行者123 更新时间:2023-12-01 00:53:38 24 4
gpt4 key购买 nike

目标是不断地从另一个tcp服务器接收一些消息。我没有使用 python 内置的 tcp 套接字,而是改用 QTcpsocket。服务器端确认客户端连接。嗯,readyRead好像从来没有发出过,不知道出了什么问题。

我尝试过 python 内置套接字,它工作正常。

import socket
import sys
import struct
import json
import os

#crate a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Connect the socket to the port where the server is listening
server_address = ('localhost', 3336)
print('connectiong to {} port {}'.format(*server_address))
sock.connect(server_address)


file_count = 0
try:
amount_received = 0
amount_expected = 6000
while amount_received < amount_expected:
data = sock.recv(5000)
data_string = data.decode("utf-8")
#print('received {!r}'.format(data))
if data_string.find("Header") != -1:
dataChunkSize = int(data_string[data_string.find("Header")+6:data_string.find("|")])
print(dataChunkSize)

try:
out = json.loads(data_string[data_string.find("JSONSTART|")+10 : data_string.find("JSONEND")])
print(out)
file_count += 1
json_data_folder = "XXXX"
if os.path.exists(json_data_folder):
json_data_folder = os.path.join(json_data_folder, str(file_count)+'.json')
with open(json_data_folder, 'w') as outfile:
json.dump(out, outfile, sort_keys=True)
print("save")
except ValueError as e:
print(e)
data_false = data
amount_expected += len(data)

finally:
print('socket closed')
sock.close()


from PyQt5.QtCore import QDataStream, QIODevice
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtNetwork import QTcpSocket, QAbstractSocket

class Client(QDialog):
def __init__(self):
super().__init__()
self.tcpSocket = QTcpSocket(self)
self.blockSize = 0
self.makeRequest()
self.tcpSocket.waitForConnected(1000)
# send any message you like it could come from a widget text.
#self.tcpSocket.write(b'hello')

self.tcpSocket.readyRead.connect(self.dealCommunication)
self.tcpSocket.error.connect(self.displayError)

def makeRequest(self):
HOST = 'localhost'
PORT = 3336
self.tcpSocket.connectToHost(HOST, PORT, QIODevice.ReadWrite)

def dealCommunication(self):
print('Message Comming')
#data = self.tcpSocket.readAll()
instr = QDataStream(self.tcpSocket)
instr.setVersion(QDataStream.Qt_5_0)
if self.blockSize == 0:
if self.tcpSocket.bytesAvailable() < 2:
return
self.blockSize = instr.readUInt16()
if self.tcpSocket.bytesAvailable() < self.blockSize:
return
# Print response to terminal, we could use it anywhere else we wanted.
print(str(instr.readString(), encoding='utf-8'))

def displayError(self, socketError):
if socketError == QAbstractSocket.RemoteHostClosedError:
pass
else:
print(self, "The following error occurred: %s." % self.tcpSocket.errorString())


if __name__ == '__main__':
import sys

app = QApplication(sys.argv)
client = Client()
sys.exit(client.exec_())

QTcpSocket 客户端应该不断接收输入。

最佳答案

您必须删除:

self.tcpSocket.waitForConnected (1000)

在 Qt 中,waitForXXX(...) 方法是阻塞的。

Qt 中什么是阻塞?这是一个不允许执行 Qt eventloop 的任务,从而阻止异步任务执行。

这会干扰由作为异步元素的readyRead信号触发的数据接收任务。

总之,如果要使用事件循环,请勿使用 waitForXXX(...) 函数。

关于python - QTcpSocket read 未发出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56391717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com