/examples/udpclient.py

https://bitbucket.org/prologic/circuits/ · 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. """(Example) UDP Client
  5. A trivial simple example of using circuits to build a simple
  6. UDP Socket Client.
  7. This example demonstrates:
  8. * Basic Component creation.
  9. * Basic Event handling.
  10. * Basic Networking
  11. This example makes use of:
  12. * Component
  13. * Event
  14. * Manager
  15. * net.sockets.UDPClient
  16. """
  17. import optparse
  18. from circuits import handler
  19. from circuits.io import stdin
  20. from circuits.net.sockets import UDPClient
  21. from circuits import __version__ as systemVersion
  22. USAGE = "%prog [options] address:[port]"
  23. VERSION = "%prog v" + systemVersion
  24. ###
  25. ### Functions
  26. ###
  27. def parse_options():
  28. """parse_options() -> opts, args
  29. Parse any command-line options given returning both
  30. the parsed options and arguments.
  31. """
  32. parser = optparse.OptionParser(usage=USAGE, version=VERSION)
  33. parser.add_option("-b", "--bind",
  34. action="store", type="str", default="0.0.0.0:8000", dest="bind",
  35. help="Bind to address:[port]")
  36. opts, args = parser.parse_args()
  37. if len(args) < 1:
  38. parser.print_help()
  39. raise SystemExit, 1
  40. return opts, args
  41. ###
  42. ### Components
  43. ###
  44. class Client(UDPClient):
  45. def __init__(self, bind, dest):
  46. super(Client, self).__init__(bind)
  47. self.dest = dest
  48. def read(self, address, data):
  49. print "%r: %r" % (address, data.strip())
  50. @handler("read", target="stdin")
  51. def stdin_read(self, data):
  52. self.write(self.dest, data)
  53. ###
  54. ### Main
  55. ###
  56. def main():
  57. opts, args = parse_options()
  58. if ":" in opts.bind:
  59. address, port = opts.bind.split(":")
  60. bind = address, int(port)
  61. else:
  62. bind = opts.bind, 8000
  63. if ":" in args[0]:
  64. dest = args[0].split(":")
  65. dest = dest[0], int(dest[1])
  66. else:
  67. dest = args[0], 8000
  68. (Client(bind, dest=dest) + stdin).run()
  69. ###
  70. ### Entry Point
  71. ###
  72. if __name__ == "__main__":
  73. main()