Use twisted to implement the python Client

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.