public
Last active

WebSocket protocol for Diesel

  • Download Gist
README.md
Markdown

WebSocket protocol for Diesel

Not tested, but a potential echo + timeout example:

from diesel import Application, Service, until_eol, sleep, bytes
from websocket import WebSocket
import time

def skip_one():
    yield bytes(1)
    yield up(until_eol())

def hi_server():
    while True:
        inp, to = yield (skip_one, sleep(3))
        if to:
            yield '%s timeout!\n' % time.asctime()
        else:
            yield 'you said %s' % inp

app = Application()
app.add_service(Service(WebSocket(hi_server), 8000))
app.run()
websocket.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
'''
Websocket for Diesel.
'''
 
from diesel import until
 
BEGINFRAME, ENDFRAME = '\x00', '\xff'
HANDSHAKE = '''\
HTTP/1.1 101 Web Socket Protocol Handshake\r\n\
Upgrade: WebSocket\r\n\
Connection: Upgrade\r\n'''
 
class WebSocketError(Exception): pass
 
class Request(object):
'''WebSocket request.
'''
def __init__(self, method, path, version):
self.method, self.path, self.version = method, path, version
 
def parse_headers(self, headers):
self.headers = dict([
line.split(': ')
for line in headers.split('\r\n')
])
 
class WebSocket(object):
'''WebSocket service.
'''
 
def __init__(self, app):
self.app = app()
 
def __call__(self, addr):
'''WebSocket handler.
'''
yield HANDSHAKE
 
request_line = yield until('\r\n')
headers = yield until('\r\n\r\n')
req = Request(*request_line.strip().split(' '))
req.parse_headers(headers.strip())
 
origin = 'WebSocket-Origin: %s' % req.headers['Origin']
loc = 'WebSocket-Location: ws://%s' % req.headers['Host'] + req.path
yield '%s\r\n%s\r\n\r\n' % (origin, loc)
 
while True:
start, out = yield (bytes(1), self.app.next())
if start:
if not start == BEGINFRAME:
raise WebSocketError()
incoming = yield (until(ENDFRAME))
self.app.send(incoming)
else:
yield out

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.