# websocket_server -- WebSocket/HTTP server/client library
# https://github.com/CylonicRaider/websocket-server

"""
Example usage of the WebSocket (and HTTP) server functionality.

To run:
- python3 -m websocket_server.examples.server
- Open http://localhost:8080/ in your WebSocket-enabled Web browser.
"""

import pkgutil

from ..exceptions import ProtocolError
from ..httpserver import RouteSet, HTTPError # FileCache not used for now
from ..quick import RoutingWebSocketRequestHandler, run

route = RouteSet()

@route('/echo')
def handle_echo(self):
    "Accept a WebSocket connection and bounce received messages back."
    try:
        conn = self.handshake()
    except ProtocolError:
        raise HTTPError(400)
    # Read frames, and write them back.
    while 1:
        try:
            msg = conn.read_frame()
            if not msg: break
            conn.write_frame(msg[0], msg[1])
        except ProtocolError as exc:
            self.log_error('%r', exc)
            break

@route('/')
def route_root(self):
    "Serve a static page at the root."
    page = pkgutil.get_data(__package__, 'testpage.html')
    self.send_text(200, page, 'text/html; charset=utf-8')

def main():
    """
    Run the example. Uses the run() function from the quick module.
    """
    run(route.build(RoutingWebSocketRequestHandler))

if __name__ == '__main__': main()

@@ -302,16 +302,33 @@
 r.%0A%22%22%22%0A%0A
+import threading%0A
 import p
@@ -334,16 +334,16 @@
 pkgutil%0A
-
 %0Afrom ..
@@ -505,16 +505,1452 @@
 r, run%0A%0A
+class MessageRelay(object):%0A    %22%22%22%0A    An elementary broadcasting message distributor.%0A%0A    Processes (e.g. connection handler threads) wishing to receive messages%0A    subscribe/unsubscribe using the listen()/unlisten() methods, respectively;%0A    processes wishing to send messages do so via the broadcast() method.%0A%0A    The constructor takes no arguments.%0A    %22%22%22%0A%0A    def __init__(self):%0A        %22Instance initializer; see the class docstring for details.%22%0A        self.clients = set()%0A        self.lock = threading.RLock()%0A%0A    def listen(self, callback):%0A        %22%22%22%0A        Register the given callback for receiving messages.%0A%0A        When a message is broadcast(), the callback is invoked upon the%0A        message object.%0A        %22%22%22%0A        with self.lock:%0A            self.clients.add(callback)%0A%0A    def unlisten(self, callback):%0A        %22%22%22%0A        Cancel the given callback's registration for receiving messages.%0A%0A        callback must be an object that had been passed to listen()%0A        previously; if it is not, it is ignored.%0A        %22%22%22%0A        with self.lock:%0A            self.clients.discard(callback)%0A%0A    def broadcast(self, message):%0A        %22%22%22%0A        Distribute the given message to all registered callbacks.%0A        %22%22%22%0A        with self.lock:%0A            for c in self.clients:%0A                try:%0A                    c(message)%0A                except Exception:%0A                    self.clients.discard(c)%0A%0A
 route = 
@@ -2215,28 +2215,28 @@
     
-while 1:%0A        try
+try:%0A        while 1
 :%0A  
@@ -2335,113 +2335,809 @@
 (msg
-%5B0%5D, msg%5B1%5D)%0A        except ProtocolError as exc:%0A            self.log_error('%25r', exc)%0A            break
+.msgtype, msg.content)%0A    except ProtocolError as exc:%0A        self.log_error('%25r', exc)%0A    finally:%0A        conn.close()%0A%0A@route('/chat')%0Adef handle_chat(self):%0A    %22Accept a WebSocket connection and broadcast received messages.%22%0A    def callback(message):%0A        %22Callback for the message relay.%22%0A        conn.write_frame(message%5B0%5D, message%5B1%5D)%0A    try:%0A        conn = self.handshake()%0A    except ProtocolError:%0A        raise HTTPError(400)%0A    # Read frames, broadcast them into the relay.%0A    try:%0A        self.relay.listen(callback)%0A        while 1:%0A            msg = conn.read_frame()%0A            if not msg: break%0A            self.relay.broadcast(msg)%0A    except ProtocolError as exc:%0A        self.log_error('%25r', exc)%0A    finally:%0A        self.relay.unlisten(callback)%0A        conn.close()
 %0A%0A@r
@@ -3416,24 +3416,24 @@
 le.%0A    %22%22%22%0A
-
     run(rout
@@ -3470,16 +3470,63 @@
 tHandler
+,%0A                    %7B'relay': MessageRelay()%7D
 ))%0A%0Aif _

Add elementary chat server to examples