/examples/udpclient.py
Python | 101 lines | 41 code | 24 blank | 36 comment | 6 complexity | 648b7f2b68f51c0a84f348c15f4c1b08 MD5 | raw file
1#!/usr/bin/env python 2# -*- coding: utf-8 -*- 3# vim: set sw=3 sts=3 ts=3 4 5"""(Example) UDP Client 6 7A trivial simple example of using circuits to build a simple 8UDP Socket Client. 9 10This example demonstrates: 11 * Basic Component creation. 12 * Basic Event handling. 13 * Basic Networking 14 15This example makes use of: 16 * Component 17 * Event 18 * Manager 19 * net.sockets.UDPClient 20""" 21 22import optparse 23 24from circuits import handler 25from circuits.io import stdin 26from circuits.net.sockets import UDPClient 27from circuits import __version__ as systemVersion 28 29USAGE = "%prog [options] address:[port]" 30VERSION = "%prog v" + systemVersion 31 32### 33### Functions 34### 35 36def parse_options(): 37 """parse_options() -> opts, args 38 39 Parse any command-line options given returning both 40 the parsed options and arguments. 41 """ 42 43 parser = optparse.OptionParser(usage=USAGE, version=VERSION) 44 45 parser.add_option("-b", "--bind", 46 action="store", type="str", default="0.0.0.0:8000", dest="bind", 47 help="Bind to address:[port]") 48 49 opts, args = parser.parse_args() 50 51 if len(args) < 1: 52 parser.print_help() 53 raise SystemExit, 1 54 55 return opts, args 56 57### 58### Components 59### 60 61class Client(UDPClient): 62 63 def __init__(self, bind, dest): 64 super(Client, self).__init__(bind) 65 66 self.dest = dest 67 68 def read(self, address, data): 69 print "%r: %r" % (address, data.strip()) 70 71 @handler("read", target="stdin") 72 def stdin_read(self, data): 73 self.write(self.dest, data) 74 75### 76### Main 77### 78 79def main(): 80 opts, args = parse_options() 81 82 if ":" in opts.bind: 83 address, port = opts.bind.split(":") 84 bind = address, int(port) 85 else: 86 bind = opts.bind, 8000 87 88 if ":" in args[0]: 89 dest = args[0].split(":") 90 dest = dest[0], int(dest[1]) 91 else: 92 dest = args[0], 8000 93 94 (Client(bind, dest=dest) + stdin).run() 95 96### 97### Entry Point 98### 99 100if __name__ == "__main__": 101 main()