Skip to content

Instantly share code, notes, and snippets.

@zeekay
Created September 16, 2011 10:12
Show Gist options
  • Save zeekay/1221752 to your computer and use it in GitHub Desktop.
Save zeekay/1221752 to your computer and use it in GitHub Desktop.
bottle_websocket.py
from bottle import ServerAdapter
from bottle import request
import json
def websocket(callback):
def wrapper(*args, **kwargs):
ws = request.environ['wsgi.websocket']
ws.json = lambda x: ws.send(json.dumps(x))
rv = callback(ws, *args, **kwargs)
return rv
return wrapper
class PolicyServer(object):
policy = """<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" to-ports="*"/>
</cross-domain-policy>"""
def __init__(self, gevent=False, listen=('0.0.0.0', 843)):
if gevent:
from gevent.server import StreamServer
self.server = StreamServer(listen, self.handle)
else:
import SocketServer
self.server = SocketServer.ThreadingTCPServer(listen, self.handle)
def handle(self, socket, address, instance=None):
fd = socket.makefile()
fd.write(self.policy)
def serve_forever(self):
self.server.serve_forever()
def start(self):
self.server.start()
class GeventWebSocketServer(ServerAdapter):
def run(self, handler):
from gevent import pywsgi, monkey
from geventwebsocket.handler import WebSocketHandler
monkey.patch_all()
server = pywsgi.WSGIServer((self.host, self.port), handler, handler_class=WebSocketHandler)
if self.options.get('policy_server', False):
PolicyServer(gevent=True).start()
server.serve_forever()
class MeinheldWebSocketServer(ServerAdapter):
def run(self, handler):
from meinheld import middleware, patch, server
patch.patch_all()
server.listen((self.host, self.port))
if self.options.get('policy_server', False):
from multiprocessing import Process
Process(target=PolicyServer().serve_forever).start()
server.run(middleware.WebSocketMiddleware(handler))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment