Commits

Jeffrey Gelens committed 975de60

Update of plot_graph example as WebSocketApplication

Comments (0)

Files changed (7)

examples/plot_graph.py

 
 
 import gevent
-import logging
 import random
 
 from geventwebsocket.server import WebSocketServer
+from geventwebsocket.resource import WebSocketApplication, Resource
 
 
-logger = logging.getLogger(__name__)
-logger = logging.getLogger(__name__)
-logger.setLevel(logging.DEBUG)
-
-def handle(ws):
-    """
-    This is the websocket handler function. Note that we can dispatch based on
-    path in here, too.
-    """
-
-    if ws.path == "/echo":
-        while True:
-            m = ws.receive()
-            if m is None:
-                break
-            ws.send(m)
-
-    elif ws.path == "/data":
+class PlotApplication(WebSocketApplication):
+    def on_open(self):
         for i in xrange(10000):
-            ws.send("0 %s %s\n" % (i, random.random()))
+            self.ws.send("0 %s %s\n" % (i, random.random()))
             gevent.sleep(0.1)
 
 
-def app(environ, start_response):
-    if environ["PATH_INFO"] == "/":
-        start_response("200 OK", [("Content-Type", "text/html")])
-        return open("plot_graph.html").readlines()
-    elif environ["PATH_INFO"] in ("/data", "/echo"):
-        handle(environ["wsgi.websocket"])
-    else:
-        start_response("404 Not Found", [])
-        return []
+def static_wsgi_app(environ, start_response):
+    start_response("200 OK", [("Content-Type", "text/html")])
+    return open("plot_graph.html").readlines()
 
 
 if __name__ == "__main__":
-    server = WebSocketServer(('', 8000), app, debug=True)
+    resource = Resource(apps={
+        '/': static_wsgi_app,
+        '/data': PlotApplication
+    })
+    server = WebSocketServer(('', 8000), resource, debug=True)
     server.serve_forever()

examples/wamp.py

-from geventwebsocket.server import WebSocketServer
-from geventwebsocket.resource import Resource, WebSocketApplication
-from geventwebsocket.protocols.wamp import WampProtocol, export_rpc
-
-
-class RPCTestClass(object):
-    @export_rpc
-    def mult(self, x, y):
-        return x * y
-
-
-class WampApplication(WebSocketApplication):
-    def on_open(self):
-        self.wamp.register_procedure("http://localhost:8000/calc#add", self.add)
-        self.wamp.register_object("http://localhost:8000/test#", RPCTestClass)
-        self.wamp.send_welcome()
-        print "opened"
-
-    def on_message(self, message):
-        print "message: ", message
-        super(WampApplication, self).on_message(message)
-
-    def on_close(self):
-        print "closed"
-
-    def add(self, var, has):
-        has.update({'bloep': var})
-        return has
-
-    def build_protocol(self):
-        self.wamp = WampProtocol(self)
-        return self.wamp
-
-    @classmethod
-    def protocol(cls):
-        return WampProtocol.PROTOCOL_NAME
-
-
-if __name__ == "__main__":
-    resource = Resource(apps={
-        '/': WampApplication
-    })
-
-    server = WebSocketServer(("", 8000), resource, debug=True)
-    server.serve_forever()

examples/wamp_example.py

+from geventwebsocket.server import WebSocketServer
+from geventwebsocket.resource import Resource, WebSocketApplication
+from geventwebsocket.protocols.wamp import WampProtocol, export_rpc
+
+
+class RPCTestClass(object):
+    @export_rpc
+    def mult(self, x, y):
+        return x * y
+
+
+class WampApplication(WebSocketApplication):
+    def on_open(self):
+        self.wamp.register_procedure("http://localhost:8000/calc#add", self.add)
+        self.wamp.register_object("http://localhost:8000/test#", RPCTestClass)
+        self.wamp.send_welcome()
+        print "opened"
+
+    def on_message(self, message):
+        print "message: ", message
+        super(WampApplication, self).on_message(message)
+
+    def on_close(self):
+        print "closed"
+
+    def add(self, var, has):
+        has.update({'bloep': var})
+        return has
+
+    def build_protocol(self):
+        self.wamp = WampProtocol(self)
+        return self.wamp
+
+    @classmethod
+    def protocol(cls):
+        return WampProtocol.PROTOCOL_NAME
+
+
+if __name__ == "__main__":
+    resource = Resource(apps={
+        '/': WampApplication
+    })
+
+    server = WebSocketServer(("", 8000), resource, debug=True)
+    server.serve_forever()

geventwebsocket/handler.py

 
         # Check for WebSocket Protocols
         requested_protocols = self.environ.get('HTTP_SEC_WEBSOCKET_PROTOCOL', '')
+        protocol = None
 
         if hasattr(self.application, 'app_protocol'):
             allowed_protocol = self.application.app_protocol(self.environ['PATH_INFO'])
-            if allowed_protocol in requested_protocols:
+
+            if allowed_protocol and allowed_protocol in requested_protocols:
                 protocol = allowed_protocol
                 self.logger.debug("Protocol allowed: {0}".format(protocol))
-            else:
-                protocol = ''
-        else:
-            protocol = ''
 
         self.websocket = WebSocket(self.environ, Stream(self), self)
         self.environ.update({
         headers = [
             ("Upgrade", "websocket"),
             ("Connection", "Upgrade"),
-            ("Sec-WebSocket-Protocol", protocol),
             ("Sec-WebSocket-Accept", base64.b64encode(
                 hashlib.sha1(key + self.GUID).digest())),
         ]
 
+        if protocol:
+            headers.append(("Sec-WebSocket-Protocol", protocol))
+
         self.logger.debug("WebSocket request accepted, switching protocols")
         self.start_response("101 Switching Protocols", headers)
 

geventwebsocket/protocols/base.py

+
+class BaseProtocol(object):
+    PROTOCOL_NAME = ""
+
+    def __init__(self, app):
+        self._app = app
+
+    def on_open(self):
+        self.app.on_open()
+
+    def on_message(self, message):
+        self.app.on_message(message)
+
+    def on_close(self):
+        self.app.on_close()
+
+    @property
+    def app(self):
+        if self._app:
+            return self._app
+        else:
+            raise Exception("No application coupled")
+

geventwebsocket/protocols/wamp.py

 import types
 import json
 
+from .base import BaseProtocol
+
 
 def export_rpc(arg=None):
    if type(arg) is types.FunctionType:
             raise Exception("no such uri '{}'".format(uri))
 
 
-class WampProtocol(object):
+class WampProtocol(BaseProtocol):
     MSG_WELCOME = 0;
     MSG_PREFIX = 1;
     MSG_CALL = 2;
 
     PROTOCOL_NAME = "wamp"
 
-    def __init__(self, app):
-        self._app = app
+    def __init__(self, *args, **kwargs):
         self.procedures = RemoteProcedures()
         self.prefixes = Prefixes()
+        self.session_id = "3434324"  # TODO generate
 
-        self.session_id = "3434324"  # TODO generate
+        super(WampProtocol, self).__init__(*args, **kwargs)
 
     def _serialize(self, data):
         return json.dumps(data)
     def on_close(self):
         self.app.on_close()
 
-    @property
-    def app(self):
-        if self._app:
-            return self._app
-        else:
-            raise Exception("No application coupled")
-

geventwebsocket/resource.py

+from .protocols.base import BaseProtocol
 from .exceptions import WebSocketError
 
 
     def on_message(self, message, *args, **kwargs):
         self.ws.send(message, **kwargs)
 
+    def build_protocol(self):
+        return BaseProtocol(self)
+
     @classmethod
     def protocol(self):
         return ''
         else:
             raise Exception("No apps defined")
 
+    def call(self, environ, start_response):
+        if self.environ['PATH_INFO'] in self.apps:
+            return self.apps[self.environ['PATH_INFO']](environ, start_response)
+        else:
+            raise Exception("No apps defined")
+
     def __call__(self, environ, start_response):
         self.environ = environ
-        self.listen()
+
+        if 'wsgi.websocket' in self.environ:
+            self.listen()
+
+            return None
+        else:
+            return self.call(environ, start_response)