/docs/source/guides/server.rst
ReStructuredText | 109 lines | 68 code | 41 blank | 0 comment | 0 complexity | daaf5d16fc4cd6f272b52f54c889aaab MD5 | raw file
1How to build a Simple Server 2============================ 3 4 5Overview 6-------- 7 8In this guide we're going to walk through the steps required to build a 9simple chat server. Users will connect using a standard telnet client and 10start chatting with other users that are connected. 11 12 13Prerequisites 14............. 15 16- `Python <http://www.python.org>`_ 17- `circuits <http://pypi.python.org/circuits>`_ 18 19 20Components 21.......... 22 23- :py:class:`~circuits.core.components.Component` 24- :py:class:`~circuits.net.sockets.TCPServer` 25 26 27Step 1 - Setting up 28------------------- 29 30Let's start off by importing the components we need: 31 32.. code-block:: python 33 34 #!/usr/bin/env python 35 36 from circuits import Component 37 from circuits.net.sockets import TCPServer, Write 38 39 40Step 2 - Building the Server 41---------------------------- 42 43Next let's define our ``Server`` Component with a simple event handler that 44broadcats all incoming messages to every connected client. 45 46.. code-block:: python 47 48 class Server(Component): 49 50 def __init__(self, host, port=8000): 51 super(Server, self).__init__() 52 53 self._clients = [] 54 55 TCPServer((host, port)).register(self) 56 57 def connect(self, sock, host, port): 58 self._clients.append(sock) 59 60 def disconnect(self, sock): 61 self._clients.remove(sock) 62 63 def read(self, sock, data): 64 for client in self._clients: 65 if not client == sock: 66 self.fire(Write(client, data.strip())) 67 68Server("localhost").run() 69Let's walk through this in details: 70 711. Create a new Component called ``Server`` 722. Define its initialization arguments as ``(host, port=8000)`` 733. Call the super constructor of the underlying Component 74 (*This is important as all components need to be initialized properly*) 754. Register a ``TCPServer`` Component and configure it. 765. Create Event Handlers for: 77 78 - Dealgin with new connecting clients. 79 - Dealing with clients whom have disconnected 80 - Dealing with messages from connected clients 81 82 83Step 3 - Running the Server 84--------------------------- 85 86The last step is simply to create an instance of the ``Server`` Component 87and run it (*making sure to configure it with a host and port*). 88 89.. code-block:: python 90 91 Server("localhost").run() 92 93That's it! 94 95Using a standard telnet client try connecting to localhost on port 8000. 96Try connecting a second client and watch what happens in the 2nd client 97when you type text into the 1st. 98 99Enjoy! 100 101 102Source Code 103----------- 104 105.. literalinclude:: server.py 106 :language: python 107 :linenos: 108 109:download:`Download server.py <server.py>`