Bottle + WebSocket

redman picture redman · Apr 25, 2012 · Viewed 8.9k times · Source

is it possible to host a normal Bottle application and a WebSocket one (example: https://github.com/defnull/bottle/blob/master/docs/async.rst) in the same application (same port)? So that /ws will go to WebSocket handler and all other will be normally routed to other bottle handlers.

Answer

Bryan Hunt picture Bryan Hunt · Jun 19, 2012

It sure is.

The server:

#!/usr/bin/python

import json
from bottle import route, run, request, abort, Bottle ,static_file
from pymongo import Connection
from gevent import monkey; monkey.patch_all()
from time import sleep

app = Bottle()

@app.route('/websocket')
def handle_websocket():
    wsock = request.environ.get('wsgi.websocket')
    if not wsock:
        abort(400, 'Expected WebSocket request.')
    while True:
        try:
            message = wsock.receive()
            wsock.send("Your message was: %r" % message)
            sleep(3)
            wsock.send("Your message was: %r" % message)
        except WebSocketError:
            break

@app.route('/<filename:path>')
def send_html(filename):
    return static_file(filename, root='./static', mimetype='text/html')


from gevent.pywsgi import WSGIServer
from geventwebsocket import WebSocketHandler, WebSocketError

host = "127.0.0.1"
port = 8080

server = WSGIServer((host, port), app,
                    handler_class=WebSocketHandler)
print "access @ http://%s:%s/websocket.html" % (host,port)
server.serve_forever()

The html page that holds the javascript:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <script type="text/javascript">
    var ws = new WebSocket("ws://localhost:8080/websocket");
    ws.onopen = function() {
        ws.send("Hello, world");
    };
    ws.onmessage = function (evt) {
        alert(evt.data);
    };
  </script>
</head>
<body>
</body>
</html>

A client:

#!/usr/bin/python

from websocket import create_connection
ws = create_connection("ws://localhost:8080/websocket")
print "Sending 'Hello, World'..."
ws.send("Hello, World")
print "Sent"
print "Reeiving..."
result =  ws.recv()
print "Received '%s'" % result
ws.close()