Skip to content

Instantly share code, notes, and snippets.

@saghul
Created July 9, 2013 22:28
  • Star 8 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save saghul/5961882 to your computer and use it in GitHub Desktop.
WSGI + WebSocket + static files Twisted example
import os
from autobahn.resource import WebSocketResource, WSGIRootResource
from autobahn.websocket import WebSocketServerFactory, WebSocketServerProtocol
from flask import Flask, render_template
from twisted.application import internet, service
from twisted.internet import reactor
from twisted.python.threadpool import ThreadPool
from twisted.web.server import Site
from twisted.web.static import File
from twisted.web.wsgi import WSGIResource
import settings
class EchoServerProtocol(WebSocketServerProtocol):
def onMessage(self, msg, binary):
self.sendMessage(msg, binary)
app = Flask('Echo Test')
@app.route('/')
def index():
return render_template('index.html', ws_port=settings.PORT)
# create a Twisted Web resource for our WebSocket server
ws_factory = WebSocketServerFactory("ws://%s:%d" % (settings.INTERFACE, settings.PORT))
ws_factory.protocol = EchoServerProtocol
ws_resource = WebSocketResource(ws_factory)
# create thread pool used to serve WSGI requests
thread_pool = ThreadPool(maxthreads=settings.THREAD_POOL_SIZE)
thread_pool.start()
reactor.addSystemEventTrigger('before', 'shutdown', thread_pool.stop)
# create a Twisted Web WSGI resource for our Flask server
wsgi_resource = WSGIResource(reactor, thread_pool, app)
# create resource for static assets
static_resource = File(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates', 'assets'))
# create a root resource serving everything via WSGI/Flask, but
# the path "/assets" served by our File stuff and
# the path "/ws" served by our WebSocket stuff
root_resource = WSGIRootResource(wsgi_resource, {'assets': static_resource, 'ws': ws_resource})
# create a Twisted Web Site
site = Site(root_resource)
# setup an application for serving the site
web_service = internet.TCPServer(settings.PORT, site, interface=settings.INTERFACE)
application = service.Application("Echo Test")
web_service.setServiceParent(application)
<html>
<head>
<link rel="stylesheet" type="text/css" href="/assets/style.css">
<script type="text/javascript">
var sock = null;
var ellog = null;
window.onload = function() {
ellog = document.getElementById('log');
var wsuri = "ws://" + window.location.hostname + ":{{ ws_port }}/ws";
if ("WebSocket" in window) {
sock = new WebSocket(wsuri);
} else {
log("Browser does not support WebSocket!");
window.location = "http://autobahn.ws/unsupportedbrowser";
}
if (sock) {
sock.onopen = function() {
log("Connected to " + wsuri);
}
sock.onclose = function(e) {
log("Connection closed (wasClean = " + e.wasClean + ", code = " + e.code + ", reason = '" + e.reason + "')");
sock = null;
}
sock.onmessage = function(e) {
log("Got echo: " + e.data);
}
}
};
function send() {
var msg = document.getElementById('message').value;
if (sock) {
sock.send(msg);
log("Sent: " + msg);
} else {
log("Not connected.");
}
};
function log(m) {
ellog.innerHTML += m + '\n';
ellog.scrollTop = ellog.scrollHeight;
};
</script>
</head>
<body>
<h1>Echo Test</h1>
<noscript>You must enable JavaScript</noscript>
<form>
<p>Message: <input id="message" type="text" size="50" maxlength="50" value="Hello, world!"></p>
</form>
<button onclick='send();'>Send Message</button>
<pre id="log" style="height: 20em; overflow-y: scroll;"></pre>
</body>
</html>
# Make sure this file is valid Python code
PORT = 8081
INTERFACE = "0.0.0.0"
THREAD_POOL_SIZE = 10
body {
font-family: Helvetica,Arial,sans-serif;
background-color:#b0c4de;
}
@sanderfoobar
Copy link

This is helpful. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment