Skip to content

Instantly share code, notes, and snippets.

@gleicon
Created March 30, 2010 09:15
Show Gist options
  • Save gleicon/348942 to your computer and use it in GitHub Desktop.
Save gleicon/348942 to your computer and use it in GitHub Desktop.
# coding: utf-8
import re
from socket import socket, SO_REUSEADDR, SOL_SOCKET
from threading import Thread
class WebSocketServer(Thread):
HDR_ORIGIN = re.compile('Origin\:\s+(.*)')
HDR_LOCATION = re.compile('GET\s+(.*)\s+HTTP\/1.1', re.I)
HDR_HOST = re.compile('Host\:\s+(.*)')
def __init__(self, sock, port=8080, host='localhost'):
self.hdr = '''HTTP/1.1 101 Web Socket Protocol Handshake\r
Upgrade: WebSocket\r
Connection: Upgrade\r
WebSocket-Origin: %s\r
WebSocket-Location: ws://%s%s\r\n\r\n'''
self.port=port
self.host=host
assert sock
self.sock=sock
self.file=sock.makefile('rwb')
Thread.__init__(self)
def run(self):
line=self.sock.recv(1024)
origin, location, host = self._parseHeaders(line)
print self.hdr % (origin, host, location)
self.sock.send(self.hdr % (origin, host, location))
# echoes back
# this should be where functions must be called (what to do when receiving stuff)
while(1):
lin=self.file.read().split('\xff') # should be a way to change delimiters from \r\n to >
for l in lin:
self._write(l)
def _parseHeaders(self, buf):
o=None
l=None
h=None
for a in buf.split('\n\r'):
print a
org=self.HDR_ORIGIN.search(a)
loc=self.HDR_LOCATION.search(a)
hst=self.HDR_HOST.search(a)
if org != None:
o=org.group(1).strip()
if hst != None:
h=hst.group(1).strip()
if loc != None:
l=loc.group(1).strip()
return o,l,h
def _write(self, str):
if self.sock == None:
print 'No handler'
else:
self.sock.send('\x00%s\xff' % str)
s = socket()
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(('', 8888));
s.listen(1);
while 1:
t,_ = s.accept()
WebSocketServer(t).start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment