How to do it...

In the Python Diesel framework, applications are initialized with an instance of the Application() class and an event handler is registered with this instance. Let's see how simple it is to write an echo server.

Listing 2.5 shows the code on the echo server example using Diesel as follows:

#!/usr/bin/env python 
# Python Network Programming Cookbook, Second Edition -- Chapter - 2 
# This program is optimized for Python 2.7.12. 
# It will work with Python 3.5.2 once the depedencies for diesel are sorted out. 
# It may run on any other version with/without modifications. 
# You also need diesel library 3.0 or a later version. 
# Make sure to install the dependencies beforehand. 
 
import diesel 
import argparse 
 
class EchoServer(object): 
    """ An echo server using diesel""" 
 
    def handler(self, remote_addr): 
        """Runs the echo server""" 
        host, port = remote_addr[0], remote_addr[1] 
        print ("Echo client connected from: %s:%d" %(host, port)) 
         
        while True: 
            try: 
                message = diesel.until_eol() 
                your_message = ': '.join(['You said', message]) 
                diesel.send(your_message) 
            except Exception as e: 
                print ("Exception:",e) 
                 
 
def main(server_port): 
    app = diesel.Application() 
    server = EchoServer()     
    app.add_service(diesel.Service(server.handler, server_port)) 
    app.run() 
 
 
if __name__ == '__main__': 
    parser = argparse.ArgumentParser(description='Echo server 
example with Diesel') parser.add_argument('--port', action="store", dest="port",
type=int, required=True) given_args = parser.parse_args() port = given_args.port main(port)

If you run this script, the server will show the following output:

$ python 12_5_echo_server_with_diesel.py --port=8800
[2017/06/04 13:37:36] {diesel} WARNING|Starting diesel <hand-rolled select.epoll>
    
    
Echo client connected from: 127.0.0.1:57506  

On another console window, another telnet client can be launched and the echoing message to our server can be tested as follows:

$ telnet localhost 8800
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello Diesel server ?
You said: Hello Diesel server ? 

The following screenshot illustrates the interaction of the Diesel chat server:

Chat Server and Telnet
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.195.97