Skip to content

added Asyncore classes #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 54 additions & 1 deletion SimpleWebSocketServer/SimpleWebSocketServer.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'''
The MIT License (MIT)
Copyright (c) 2013 Dave P.
Asyncore addition by Arnaud Loonstra
'''
import sys
VER = sys.version_info[0]
Expand All @@ -22,10 +23,13 @@
import codecs
from collections import deque
from select import select
import asyncore

__all__ = ['WebSocket',
'SimpleWebSocketServer',
'SimpleSSLWebSocketServer']
'SimpleSSLWebSocketServer',
'AsyncoreWebSocketServer',
'AsyncoreWebSocketServerHandler']

def _check_unicode(val):
if VER >= 3:
Expand Down Expand Up @@ -692,3 +696,52 @@ def _constructWebSocket(self, sock, address):

def serveforever(self):
super(SimpleSSLWebSocketServer, self).serveforever()


class AsyncoreWebSocketServer(asyncore.dispatcher):

def __init__(self, host, port, websockethandler):
asyncore.dispatcher.__init__(self)
self.host = host
self.port = port
self.handler = websockethandler
self.create_socket (socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)

def handle_accept(self):
try:
conn, addr = self.accept()
except socket.error:
print('warning: server accept() threw an exception')
return
except TypeError:
print('warning: server accept() threw EWOULDBLOCK')
return
# creates an instance of the handler class to handle the request/response
# on the incoming connexion
self.handler(self, conn, addr)


class AsyncoreWebSocketServerHandler(WebSocket, asyncore.dispatcher):

def __init__(self, server, sock, address):
asyncore.dispatcher.__init__(self, sock)
WebSocket.__init__(self, server, sock, address)

def handle_read(self):
try:
self._handleData()
while self.sendq:
opcode, payload = self.sendq.popleft()
remaining = self._sendBuffer(payload)
if remaining is not None:
self.sendq.appendleft((opcode, remaining))
break
else:
if opcode == CLOSE:
raise Exception('received client close')
except Exception as n:
asyncore.dispatcher.close(self)
self.handleClose()