This section describes the Server framework. The code in the client can reuse its package. py and dispatch. py.
The server is generally running on the console, but most of the clients are with the UI.
Here we will introduce
1. Console
Start main. py on the client
Here, pyconfigure is not described.
from config import *from tcp import *def main():#[0] load configure json cfg = PyConfigure( "cfg.json" ) host = cfg.get_value( "host" ) port = cfg.get_value( "port" )#[1] connect server factory = PyClientFactory() try: reactor.connectTCP( host, port, factory ) reactor.run() except: print "connect server error."if __name__ == '__main__': main()
The client implements TCP. py
from twisted.internet.protocol import ClientFactory, Protocolfrom twisted.protocols.basic import LineReceiverfrom twisted.internet import reactorfrom twisted.internet.endpoints import TCP4ClientEndpointimport sysimport structfrom dispatch import *class PyTcpClient( Protocol ): def __init__( self ): self.dispatcher = PyDispatcher( self ) def connectionMade( self ): print "login" def connectionLost( self, reason ): print "connection lost" def dataReceived( self, data ): print "receive:", data self.dispatcher.dispatch( data ) def dataSend( self, data ): print data self.transport.write( data )class PyClientFactory( ClientFactory ): protocol = PyTcpClient def clientConnectionFailed( self, connector, reason ): print 'connection failed:', reason.getErrorMessage() reactor.stop() def clientConnectionLost( self, connector, reason ): print 'connection lost:', reason.getErrorMessage() reactor.stop()
Okay, so you can work. But the code is not concise enough.
2. UI
In fact, it is relatively simple:
reactor.run()
Put it in the thread.
The following code is used in combination with pyqt4.