Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Refactored prototype. Doesn't work like the prototype did :/

  • Loading branch information...
commit bfe2a88d8f0a6374b03e75362a21d9423dd8af77 1 parent 03122bd
Jeffrey Gelens authored
View
24 LICENSE
@@ -0,0 +1,24 @@
+Copyright (c) 2010, Noppo (Jeffrey Gelens) <http://www.noppo.pro/>
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this list
+of conditions and the following disclaimer.
+Redistributions in binary form must reproduce the above copyright notice, this
+list of conditions and the following disclaimer in the documentation and/or
+other materials provided with the distribution.
+Neither the name of the Noppo nor the names of its contributors may be
+used to endorse or promote products derived from this software without specific
+prior written permission.
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
View
0  geventsocketio/__init__.py
No changes.
View
111 geventsocketio/handler.py
@@ -0,0 +1,111 @@
+import re
+from gevent.pywsgi import WSGIHandler
+from geventsocketio import transports
+from geventsocketio.protocol import Session
+
+
+class SocketIOHandler(WSGIHandler):
+ path_re = re.compile(r"^/(?P<resource>[^/]+)/(?P<transport>[^/]+)/(?P<session_id>[^/]*)/?(?P<rest>.*)$")
+
+ handler_types = {
+ 'websocket': 'WebSocketHandler',
+ 'wsgi': WSGIHandler,
+ 'flashsocket': 'FlashSocketHandler',
+ 'htmlfile': 'HTMLFileHandler',
+ 'xhr-multipart': 'XHRMultipartHandler',
+ 'xhr-polling': transports.XHRPollingTransport,
+ 'jsonp-polling': 'JSONPollingHandler',
+ }
+
+ def __init__(self, *args, **kwargs):
+ self.socketio_connection = False
+ super(SocketIOHandler, self).__init__(*args, **kwargs)
+
+ def handle_one_response(self):
+ self.status = None
+ self.headers_sent = False
+ self.result = None
+ self.response_length = 0
+ self.response_use_chunked = False
+
+ path = self.environ.get('PATH_INFO')
+ parts = SocketIOHandler.path_re.match(path)
+
+ print "Arrived at", path
+
+ if parts:
+ parts = parts.groupdict()
+ print parts
+ else:
+ print "closed"
+ self.close_connection = True
+ return
+
+ resource = parts.get('resource')
+ transport = SocketIOHandler.handler_types.get(parts.get('transport'))
+ session_id = parts.get('session_id')
+ request_method = self.environ.get("REQUEST_METHOD")
+
+ if not transport:
+ return super(SocketIOHandler, self).handle_one_response()
+ self.transport = transport(self)
+
+ print request_method
+
+ if request_method == "GET":
+ if session_id == '':
+ # Create a new session and close connection
+ session = Session()
+ self.server.sessions[session.session_id] = session
+
+ message = self.environ['socketio']._encode(session.session_id)
+ self.start_response("200 OK", [
+ ("Connection", "close"),
+ ("Access-Control-Allow-Origin", "*"),
+ ("Content-Type", "text/plain; charset=UTF-8"),
+ ("Content-Length", len(message)),
+ ])
+ self.write(message)
+ else:
+ # Session has been found, handle this request using a Socket.IO transport
+ self.socketio_connection = True
+ session = self.server.sessions.get(session_id)
+
+ if session is None:
+ print "Close connection"
+ self.close_connection = True
+ else:
+ print "eeej?"
+ self.transport.handle_get_response()
+
+
+ elif request_method == "POST":
+ self.close_connection = True
+ #self.transport.handle_post_response()
+
+ self.socketio_connection = False
+
+ def start_response(self, status, headers, exc_info=None):
+ if self.socketio_connection:
+ self.status = status
+
+ towrite = []
+ towrite.append('%s %s\r\n' % (self.request_version, self.status))
+
+ for header in headers:
+ towrite.append("%s: %s\r\n" % header)
+
+ self.wfile.writelines(towrite)
+ self.headers_sent = True
+ else:
+ super(SocketIOHandler, self).start_response(status, headers, exc_info)
+
+ def write_more_headers(self, headers):
+ towrite = []
+
+ for header in headers:
+ towrite.append("%s: %s\r\n" % header)
+
+ towrite.append("\r\n")
+ self.wfile.writelines(towrite)
+
View
54 geventsocketio/protocol.py
@@ -0,0 +1,54 @@
+import random
+
+MSG_FRAME = "~m~"
+HEARTBEAT_FRAME = "~h~"
+JSON_FRAME = "~j~"
+
+class SocketIOProtocol(object):
+ def __init__(self, handler):
+ self.handler = handler
+
+ def send(self, message, skip_queue=True):
+ if skip_queue:
+ self.handler._send(self._encode(message))
+ else:
+ pass
+
+ def wait(self):
+ return self._decode(self.handler._wait())
+
+ def _encode(self, message):
+ return MSG_FRAME + str(len(message)) + MSG_FRAME + message
+
+ def _decode(self, data):
+ messages = []
+ #data.encode('utf-8')
+ if data is not None:
+ while len(data) != 0:
+ if messages[0:3] == MSG_FRAME:
+ null, size, data = data.split(MSG_FRAME, 2)
+ size = int(size)
+
+ frame_type = data[0:3]
+ if frame_type == JSON_FRAME:
+ pass # Do some json parsing of data[3:size]
+ elif frame_type == HFRAME:
+ pass # let the caller process the message?
+ else:
+ messages.append(data[0:size])
+
+ data = data[size:]
+ else:
+ raise Exception("Unsupported frame type")
+
+ return messages
+ else:
+ return messages
+
+
+class Session(object):
+ def __init__(self, session_id=None):
+ if session_id is None:
+ self.session_id = str(random.random())[2:]
+ else:
+ self.session_id = session_id
View
13 geventsocketio/server.py
@@ -0,0 +1,13 @@
+from gevent.pywsgi import WSGIServer
+from geventsocketio.protocol import SocketIOProtocol
+
+
+class SocketIOServer(WSGIServer):
+ def __init__(self, *args, **kwargs):
+ self.sessions = {}
+ super(SocketIOServer, self).__init__(*args, **kwargs)
+
+ def handle(self, socket, address):
+ handler = self.handler_class(socket, address, self)
+ self.set_environ({'socketio': SocketIOProtocol(handler)})
+ handler.handle()
View
35 geventsocketio/transports.py
@@ -0,0 +1,35 @@
+import gevent
+
+
+class XHRPollingTransport(object):
+ def __init__(self, handler):
+ self.handler = handler
+
+ def handle_get_response(self):
+ self.handler.start_response("200 OK", [("Access-Control-Allow-Origin", "*"),])
+
+ print "wrote header"
+
+ gevent.sleep(5)
+ self.handler.write_more_headers([
+ ("Connection", "close"),
+ ("Content-Type", "text/plain; charset=UTF-8"),
+ ("Content-Length", '0'),
+ ])
+ self.handler.write("\r\n")
+ self.handler.close_connection = True
+
+ def handle_post_response(self):
+ #data = self.handler.wsgi_input.readline()
+ print "POST data", data
+ #self.handler.socketio_connection = False
+ self.handler.start_response("200 OK", [("Access-Control-Allow-Origin", "*"),])
+
+ print "wrote header"
+
+ self.handler.write_more_headers([
+ ("Connection", "close"),
+ ("Content-Type", "text/plain; charset=UTF-8"),
+ ("Content-Length", '2'),
+ ])
+ self.handler.write("\r\nok\r\n")
View
226 test.py
@@ -1,225 +1,5 @@
-import re
-import gevent
-from gevent import pywsgi
-from gevent.event import AsyncResult
-from geventwebsocket.handler import WebSocketHandler
-
-from gevent.server import StreamServer
-from gevent.pywsgi import WSGIHandler, WSGIServer
-
-from geventwebsocket.handler import WebSocketHandler
-
-
-class SocketIOServer(WSGIServer):
- def __init__(self, *args, **kwargs):
- self.sessions = {}
- super(SocketIOServer, self).__init__(*args, **kwargs)
-
- def handle(self, socket, address):
- print "new connection"
- handler = self.handler_class(socket, address, self)
- self.set_environ({'socketio': SocketIOHandler(handler)})
- handler.handle()
- print "end of connection"
-
-
-class XHRPollingHandler(WSGIHandler):
- def handle_get_response(self):
- data = None
- self.status = "200 OK"
-
- #towrite = [
- # '%s %s\r\n' % (self.request_version, "200 OK"),
- # "Access-Control-Allow-Origin: *\r\n",
- #]
- self.start_response("200 OK", [("Access-Control-Allow-Origin", "*"),])
-
- print "wrote header"
-
- gevent.sleep(5)
- self.write_headers([
- ("Connection", "close"),
- ("Content-Type", "text/plain; charset=UTF-8"),
- ("Content-Length", '0'),
- ])
- self.write("\r\n")
- self.close_connection = True
-
- def handle_post_response(self):
- self.close_connection = True
- data = self.wsgi_input.readline()
- print "POST data", data
-
- self.start_response("200 OK", [("Access-Control-Allow-Origin", "*"),])
-
- print "wrote header"
-
- self.write_headers([
- ("Connection", "close"),
- ("Content-Type", "text/plain; charset=UTF-8"),
- ("Content-Length", '2'),
- ])
- self.write("\r\nok\r\n")
- self.close_connection = True
-
-
- #def write(self, data):
- # self.wfile.writelines(data)
-
- def start_response(self, status, headers, exc_info=None):
- self.status = status
-
- towrite = []
- towrite.append('%s %s\r\n' % (self.request_version, self.status))
-
- for header in headers:
- towrite.append("%s: %s\r\n" % header)
-
- #towrite.append("\r\n")
- self.wfile.writelines(towrite)
-
- self.headers_sent = True
-
- def write_headers(self, headers):
- towrite = []
-
- for header in headers:
- towrite.append("%s: %s\r\n" % header)
-
- towrite.append("\r\n")
- self.wfile.writelines(towrite)
-
- #self.result = self.application(self.environ, self.start_response)
-
-
-class Handler(WSGIHandler):
- path_re = re.compile(r"^/(?P<resource>[^/]+)/(?P<protocol>[^/]+)/(?P<session_id>[^/]*)/?(?P<rest>.*)$")
-
- handler_types = {
- 'websocket': WebSocketHandler,
- 'wsgi': WSGIHandler,
- 'flashsocket': 'FlashSocketHandler',
- 'htmlfile': 'HTMLFileHandler',
- 'xhr-multipart': 'XHRMultipartHandler',
- 'xhr-polling': XHRPollingHandler,
- 'jsonp-polling': 'JSONPollingHandler',
- }
-
- def handle_one_response(self):
- self.status = None
- self.headers_sent = False
- self.result = None
- self.response_length = 0
- self.response_use_chunked = False
-
- path = self.environ.get('PATH_INFO')
- parts = Handler.path_re.match(path)
-
- print "Arrived at", path
-
- if parts:
- parts = parts.groupdict()
- print parts
- else:
- print "closed"
- self.close_connection = True
- return
-
- resource = parts.get('resource')
- protocol = Handler.handler_types.get(parts.get('protocol'))
- session_id = parts.get('session_id')
- request_method = self.environ.get("REQUEST_METHOD")
- self.__class__ = protocol
-
- print request_method
-
- if request_method == "GET":
- if session_id == '':
- session = Session()
- self.server.sessions[session.session_id] = session
- #self.send_one_message(session.session_id)
-
- message = self.environ['socketio']._encode(session.session_id)
- self.start_response("200 OK", [
- ("Connection", "close"),
- ("Access-Control-Allow-Origin", "*"),
- ("Content-Type", "text/plain; charset=UTF-8"),
- ("Content-Length", len(message)),
- ])
- self.write("\r\n" + message)
- self.close_connection = 1
- else:
- session = self.server.sessions.get(session_id)
-
- if session is None:
- print "Close connection"
- self.close_connection = True
- else:
- print "eeej?"
- self.handle_get_response()
-
-
- elif request_method == "POST":
- self.close_connection = True
- self.handle_post_response()
-
-
-
-MSG_FRAME = "~m~"
-HEARTBEAT_FRAME = "~h~"
-JSON_FRAME = "~j~"
-
-
-import random
-class Session(object):
- def __init__(self, session_id=None):
- if session_id is None:
- self.session_id = str(random.random())[2:]
- else:
- self.session_id = session_id
-
-
-class SocketIOHandler(object):
- def __init__(self, handler):
- self.handler = handler
-
- def send(self, message, skip_queue=True):
- if skip_queue:
- self.handler._send(self._encode(message))
- else:
- pass
-
- def wait(self):
- return self._decode(self.handler._wait())
-
- def _encode(self, message):
- return MSG_FRAME + str(len(message)) + MSG_FRAME + message
-
- def _decode(self, data):
- messages = []
- #data.encode('utf-8')
- if data is not None:
- while len(data) != 0:
- if messages[0:3] == MSG_FRAME:
- null, size, data = data.split(MSG_FRAME, 2)
- size = int(size)
-
- frame_type = data[0:3]
- if frame_type == JSON_FRAME:
- pass # Do some json parsing of data[3:size]
- elif frame_type == HFRAME:
- pass # let the caller process the message?
- else:
- messages.append(data[0:size])
-
- data = data[size:]
- else:
- raise Exception("Unsupported frame type")
-
- return messages
- else:
- return messages
-
+from geventsocketio.server import SocketIOServer
+from geventsocketio.handler import SocketIOHandler
def app(environ, start_response):
socketio = environ['socketio']
@@ -237,6 +17,6 @@ def app(environ, start_response):
-server = SocketIOServer(('', 8080), app, handler_class=Handler)
+server = SocketIOServer(('', 8080), app, handler_class=SocketIOHandler)
server.serve_forever()
Please sign in to comment.
Something went wrong with that request. Please try again.