0

我现在正试图让我的 PC 上的 GUI 与每个套接字的服务器通信。

这是GUI的部分代码:

def listenToServer(self):
    """ keep listening to the server until receiving 'All Contracts Finished' """
    self.feedbackWindow.appendPlainText('--Executing the Contracts, Listening to Server--')
    contentsListend = ''
    while contentsListend != 'All Contracts Finished':
        #keep listen from the socket
        contentsListend = self.skt.recv(1024)
        #make the GUI show the text
        self.feedbackWindow.appendPlainText(contentsListend)

另一方面,服务器将一个接一个地发送数据,但有一定的间隔。这是模拟服务器的测试代码:

for i in range(7):
    print 'send back msg, round: ', i # this will be printed on the screen of the server, to let me know that the server works
    time.sleep(1) # make some interval
    # c is the connected socket, which can send messages
    # just send the current loop number
    c.send('send back msg' + str(i))
c.send('All Contracts Finished')
c.close()# Close the connection

现在,除了在服务器中的整个 for 循环之后,GUI 只会显示接收到的消息的问题之外,一切正常。一旦我运行服务器和 GUI。服务器端以正确的速度将消息一一打印到屏幕上,但 GUI 没有响应,它不更新。直到程序结束,所有 7 行都在 GUI 端同时出现。我希望它们一一出现,以便稍后我可以在我的 PC 上使用此 GUI 检查服务器的状态。

谁能帮忙,非常感谢!

4

1 回答 1

1

这与“快”或“慢”无关。

GUI 与您的方法在同一线程上运行listenToServer- 只要它在运行,GUI 线程上就不会发生任何事情。您会注意到在等待套接字输入时,您无法在 GUI 中移动、调整大小或单击任何内容。

您必须在与 GUI 分开的线程上运行您的 listenToServer 方法。正确的方法是实现一个Worker从套接字接收数据并通过 Signal->Slot 连接通知您 textEdit 有数据准备好接收的对象。

不久前我回答了一个类似的问题,这可能会有所帮助 https://stackoverflow.com/a/24821300/2319400

一个非常快速和肮脏的替代方法是在您附加新数据时处理所有排队的事件,通过:

QApplication.processEvents()

这让 Qt 有时间在屏幕上用新文本重新绘制 GUI。但是,当 python 等待来自套接字的数据时,您的 GUI 将不会响应任何事件!

于 2015-04-22T13:41:26.770 回答