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.
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()
This most likely isn't the easiest answer but I just got done setting up a test environment that works using Nginx and uWSGI over Pyramid and once you've got it setup you can extend it very very easily, for instance if your /ws is pulling too many resources, it's trivial with Nginx+uWSGI to relocate /ws to different hardware. My background is Pyramid and my uWSGI experience has only been with testing but in my reading it seems a solution that should work well. The bottle instructions were the result of a quick google search.
The concept of serving an app to a socket as file was new to me when I was setting up the testing environment, I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With