我正在设计一个gui应用程序作为服务器的客户端,我有3个类
一个用于扭曲协议的类,另一个用于工厂,第三个用于pyqt线程。如何从pyqt线程发送数据,例如,如果单击按钮我如何使用当前的扭曲连接发送命令,这是我的代码的副本
from OpenSSL import SSL;import sys
from twisted.internet.protocol import ClientFactory
from twisted.internet import ssl, protocol
from PyQt4 import QtCore, QtGui
from gui import Ui_clientgui
class clientgui(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_clientgui()
self.ui.setupUi(self)
def closeEvent(self, e):
try:reactor.callFromThread(reactor.stop)
except:pass
class Client(protocol.Protocol):
def connectionMade(self):
global server_options
server_options['connection'] = True
def send(self,data):
self.transport.write(data)
def connectionLost(self, reason):
server_options['connection'] = False
def dataReceived(self, line):
print "receive:", line
class ClientFactory(ClientFactory):
protocol = Client
def clientConnectionFailed(self, connector, reason):
print 'connection failed'
try:reactor.stop()
except:pass
if __name__ == '__main__':
app = QtGui.QApplication([])
import qt4reactor
qt4reactor.install()
from twisted.internet import reactor
factory = ClientFactory()
reactor.connectSSL('localhost', 8080, factory, ssl.ClientContextFactory())
application = clientgui(reactor)
application.show()
reactor.runReturn()
sys.exit(app.exec_())
答案 0 :(得分:1)
如果你使用qt4reactor,你根本不需要乱用多个线程; Twisted将在QT线程中运行,它们可以自由地触及彼此的数据结构。
如果你想用线程做这个,你的例子已经包含了解决方案:reactor.callFromThread
。 (我建议您callFromThread(client.send)
而不是callFromThread(transport.write)
,因为Client
是Protocol
,因此生活在Twisted的宇宙中比Qt更多。