1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
#!/usr/bin/env python
"""Node Server Example
This example demonstrates how to create a very simple node server
that supports bi-diractional messaging between server and connected
clients forming a cluster of nodes.
"""
from __future__ import print_function
from os import getpid
from optparse import OptionParser
from circuits.node import Node
from circuits import Component, Debugger
__version__ = "0.0.1"
USAGE = "%prog [options]"
VERSION = "%prog v" + __version__
def parse_options():
parser = OptionParser(usage=USAGE, version=VERSION)
parser.add_option(
"-b", "--bind",
action="store", type="string",
default="0.0.0.0:8000", dest="bind",
help="Bind to address:[port]"
)
parser.add_option(
"-d", "--debug",
action="store_true",
default=False, dest="debug",
help="Enable debug mode"
)
opts, args = parser.parse_args()
return opts, args
class NodeServer(Component):
def init(self, args, opts):
"""Initialize our ``ChatServer`` Component.
This uses the convenience ``init`` method which is called after the
component is proeprly constructed and initialized and passed the
same args and kwargs that were passed during construction.
"""
self.args = args
self.opts = opts
self.clients = {}
if opts.debug:
Debugger().register(self)
if ":" in opts.bind:
address, port = opts.bind.split(":")
port = int(port)
else:
address, port = opts.bind, 8000
bind = (address, port)
Node(bind).register(self)
def connect(self, sock, host, port):
"""Connect Event -- Triggered for new connecting clients"""
self.clients[sock] = {
"host": sock,
"port": port,
}
def disconnect(self, sock):
"""Disconnect Event -- Triggered for disconnecting clients"""
if sock not in self.clients:
return
del self.clients[sock]
def ready(self, server, bind):
print("Ready! Listening on {}:{}".format(*bind))
print("Waiting for remote events...")
def hello(self):
return "Hello World! ({0:d})".format(getpid())
def main():
opts, args = parse_options()
# Configure and "run" the System.
NodeServer(args, opts).run()
if __name__ == "__main__":
main()
|