Merged Channel functionality into BaseNamespace
This commit is contained in:
parent
f725889de7
commit
75d1fa2adc
3 changed files with 79 additions and 88 deletions
|
|
@ -1,5 +1,7 @@
|
||||||
0.4
|
0.4
|
||||||
---
|
---
|
||||||
|
- Merged Channel functionality into BaseNamespace thanks to Alexandre Bourget
|
||||||
|
- Added support for unicode thanks to Zac Lee
|
||||||
|
|
||||||
0.3
|
0.3
|
||||||
---
|
---
|
||||||
|
|
|
||||||
|
|
@ -12,8 +12,10 @@ PROTOCOL = 1 # socket.io protocol version
|
||||||
class BaseNamespace(object): # pragma: no cover
|
class BaseNamespace(object): # pragma: no cover
|
||||||
'Define socket.io behavior'
|
'Define socket.io behavior'
|
||||||
|
|
||||||
def __init__(self, _socketIO):
|
def __init__(self, _socketIO, namespacePath):
|
||||||
self._socketIO = _socketIO
|
self._socketIO = _socketIO
|
||||||
|
self._namespacePath = namespacePath
|
||||||
|
self._callbackByEvent = {}
|
||||||
|
|
||||||
def on_connect(self):
|
def on_connect(self):
|
||||||
pass
|
pass
|
||||||
|
|
@ -27,7 +29,7 @@ class BaseNamespace(object): # pragma: no cover
|
||||||
def on_message(self, messageData):
|
def on_message(self, messageData):
|
||||||
print '[Message] %s' % messageData
|
print '[Message] %s' % messageData
|
||||||
|
|
||||||
def on_(self, eventName, *eventArguments):
|
def on_default(self, eventName, *eventArguments):
|
||||||
print '[Event] %s%s' % (eventName, eventArguments)
|
print '[Event] %s%s' % (eventName, eventArguments)
|
||||||
|
|
||||||
def on_open(self, *args):
|
def on_open(self, *args):
|
||||||
|
|
@ -42,6 +44,29 @@ class BaseNamespace(object): # pragma: no cover
|
||||||
def on_reconnect(self, *args):
|
def on_reconnect(self, *args):
|
||||||
print '[Reconnect]', args
|
print '[Reconnect]', args
|
||||||
|
|
||||||
|
def message(self, messageData, messageCallback=None):
|
||||||
|
self._socketIO.message(
|
||||||
|
messageData, messageCallback, namespacePath=self._namespacePath)
|
||||||
|
|
||||||
|
def emit(self, eventName, *eventArguments):
|
||||||
|
self._socketIO.emit(
|
||||||
|
eventName, *eventArguments, namespacePath=self._namespacePath)
|
||||||
|
|
||||||
|
def on(self, eventName, eventCallback):
|
||||||
|
self._callbackByEvent[eventName] = eventCallback
|
||||||
|
|
||||||
|
def _get_eventCallback(self, eventName):
|
||||||
|
# Check callbacks defined by on()
|
||||||
|
try:
|
||||||
|
return self._callbackByEvent[eventName]
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Check callbacks defined explicitly or use on_default()
|
||||||
|
def callback(*eventArguments):
|
||||||
|
return self.on_default(eventName, *eventArguments)
|
||||||
|
return getattr(self, 'on_' + eventName.replace(' ', '_'), callback)
|
||||||
|
|
||||||
|
|
||||||
class SocketIO(object):
|
class SocketIO(object):
|
||||||
|
|
||||||
|
|
@ -54,7 +79,7 @@ class SocketIO(object):
|
||||||
proxies={'https': 'https://proxy.example.com:8080'})
|
proxies={'https': 'https://proxy.example.com:8080'})
|
||||||
"""
|
"""
|
||||||
self._socketIO = _SocketIO(host, port, secure, proxies)
|
self._socketIO = _SocketIO(host, port, secure, proxies)
|
||||||
self._channelByPath = {}
|
self._namespaceByPath = {}
|
||||||
self.define(BaseNamespace) # Define default namespace
|
self.define(BaseNamespace) # Define default namespace
|
||||||
|
|
||||||
self._rhythmicThread = _RhythmicThread(
|
self._rhythmicThread = _RhythmicThread(
|
||||||
|
|
@ -64,7 +89,7 @@ class SocketIO(object):
|
||||||
|
|
||||||
self._listenerThread = _ListenerThread(
|
self._listenerThread = _ListenerThread(
|
||||||
self._socketIO,
|
self._socketIO,
|
||||||
self._channelByPath)
|
self._namespaceByPath)
|
||||||
self._listenerThread.start()
|
self._listenerThread.start()
|
||||||
|
|
||||||
def __enter__(self):
|
def __enter__(self):
|
||||||
|
|
@ -80,32 +105,29 @@ class SocketIO(object):
|
||||||
def connected(self):
|
def connected(self):
|
||||||
return self._socketIO.connected
|
return self._socketIO.connected
|
||||||
|
|
||||||
def disconnect(self, channelPath='', closeSocket=True):
|
def disconnect(self, namespacePath='', closeSocket=True):
|
||||||
if self.connected:
|
if self.connected:
|
||||||
self._socketIO.disconnect(channelPath, closeSocket)
|
self._socketIO.disconnect(namespacePath, closeSocket)
|
||||||
if channelPath:
|
if namespacePath:
|
||||||
del self._channelByPath[channelPath]
|
del self._namespaceByPath[namespacePath]
|
||||||
else:
|
else:
|
||||||
self._rhythmicThread.cancel()
|
self._rhythmicThread.cancel()
|
||||||
self._listenerThread.cancel()
|
self._listenerThread.cancel()
|
||||||
|
|
||||||
def define(self, Namespace, channelPath=''):
|
def define(self, Namespace, namespacePath=''):
|
||||||
self._socketIO.connect(channelPath)
|
self._socketIO.connect(namespacePath)
|
||||||
channel = Channel(self._socketIO, Namespace, channelPath)
|
namespace = Namespace(self._socketIO, namespacePath)
|
||||||
self._channelByPath[channelPath] = channel
|
self._namespaceByPath[namespacePath] = namespace
|
||||||
return channel
|
return namespace
|
||||||
|
|
||||||
def get_channel(self, channelPath=''):
|
def get_namespace(self, namespacePath=''):
|
||||||
return self._channelByPath[channelPath]
|
return self._namespaceByPath[namespacePath]
|
||||||
|
|
||||||
def get_namespace(self, channelPath=''):
|
def on(self, eventName, eventCallback, namespacePath=''):
|
||||||
return self.get_channel(channelPath).get_namespace()
|
return self.get_namespace(namespacePath).on(eventName, eventCallback)
|
||||||
|
|
||||||
def on(self, eventName, eventCallback, channelPath=''):
|
def message(self, messageData, messageCallback=None, namespacePath=''):
|
||||||
return self.get_channel(channelPath).on(eventName, eventCallback)
|
self._socketIO.message(messageData, messageCallback, namespacePath)
|
||||||
|
|
||||||
def message(self, messageData, messageCallback=None, channelPath=''):
|
|
||||||
self._socketIO.message(messageData, messageCallback, channelPath)
|
|
||||||
|
|
||||||
def emit(self, eventName, *eventArguments, **eventKeywords):
|
def emit(self, eventName, *eventArguments, **eventKeywords):
|
||||||
self._socketIO.emit(eventName, *eventArguments, **eventKeywords)
|
self._socketIO.emit(eventName, *eventArguments, **eventKeywords)
|
||||||
|
|
@ -150,10 +172,10 @@ class _ListenerThread(Thread):
|
||||||
|
|
||||||
daemon = True
|
daemon = True
|
||||||
|
|
||||||
def __init__(self, _socketIO, _channelByPath):
|
def __init__(self, _socketIO, _namespaceByPath):
|
||||||
super(_ListenerThread, self).__init__()
|
super(_ListenerThread, self).__init__()
|
||||||
self._socketIO = _socketIO
|
self._socketIO = _socketIO
|
||||||
self._channelByPath = _channelByPath
|
self._namespaceByPath = _namespaceByPath
|
||||||
self.done = Event()
|
self.done = Event()
|
||||||
self.waiting = Event()
|
self.waiting = Event()
|
||||||
|
|
||||||
|
|
@ -168,7 +190,7 @@ class _ListenerThread(Thread):
|
||||||
def run(self):
|
def run(self):
|
||||||
while not self.done.is_set():
|
while not self.done.is_set():
|
||||||
try:
|
try:
|
||||||
code, packetID, channelPath, data = self._socketIO.recv_packet()
|
code, packetID, namespacePath, data = self._socketIO.recv_packet()
|
||||||
except SocketIOConnectionError, error:
|
except SocketIOConnectionError, error:
|
||||||
print error
|
print error
|
||||||
return
|
return
|
||||||
|
|
@ -176,9 +198,9 @@ class _ListenerThread(Thread):
|
||||||
print error
|
print error
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
channel = self._channelByPath[channelPath]
|
namespace = self._namespaceByPath[namespacePath]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
print 'Received unexpected channelPath (%s)' % channelPath
|
print 'Received unexpected namespacePath (%s)' % namespacePath
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
delegate = {
|
delegate = {
|
||||||
|
|
@ -194,7 +216,7 @@ class _ListenerThread(Thread):
|
||||||
except KeyError:
|
except KeyError:
|
||||||
print 'Received unexpected code (%s)' % code
|
print 'Received unexpected code (%s)' % code
|
||||||
continue
|
continue
|
||||||
delegate(packetID, channel._get_eventCallback, data)
|
delegate(packetID, namespace._get_eventCallback, data)
|
||||||
|
|
||||||
def on_disconnect(self, packetID, get_eventCallback, data):
|
def on_disconnect(self, packetID, get_eventCallback, data):
|
||||||
get_eventCallback('disconnect')()
|
get_eventCallback('disconnect')()
|
||||||
|
|
@ -264,16 +286,16 @@ class _SocketIO(object):
|
||||||
def __del__(self):
|
def __del__(self):
|
||||||
self.disconnect(closeSocket=False)
|
self.disconnect(closeSocket=False)
|
||||||
|
|
||||||
def disconnect(self, channelPath='', closeSocket=True):
|
def disconnect(self, namespacePath='', closeSocket=True):
|
||||||
if not self.connected:
|
if not self.connected:
|
||||||
return
|
return
|
||||||
if channelPath:
|
if namespacePath:
|
||||||
self.send_packet(0, channelPath)
|
self.send_packet(0, namespacePath)
|
||||||
elif closeSocket:
|
elif closeSocket:
|
||||||
self.connection.close()
|
self.connection.close()
|
||||||
|
|
||||||
def connect(self, channelPath):
|
def connect(self, namespacePath):
|
||||||
self.send_packet(1, channelPath)
|
self.send_packet(1, namespacePath)
|
||||||
|
|
||||||
def send_heartbeat(self):
|
def send_heartbeat(self):
|
||||||
try:
|
try:
|
||||||
|
|
@ -282,14 +304,14 @@ class _SocketIO(object):
|
||||||
print 'Could not send heartbeat'
|
print 'Could not send heartbeat'
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def message(self, messageData, messageCallback, channelPath):
|
def message(self, messageData, messageCallback, namespacePath):
|
||||||
if isinstance(messageData, basestring):
|
if isinstance(messageData, basestring):
|
||||||
code = 3
|
code = 3
|
||||||
data = messageData
|
data = messageData
|
||||||
else:
|
else:
|
||||||
code = 4
|
code = 4
|
||||||
data = dumps(messageData, ensure_ascii=False)
|
data = dumps(messageData, ensure_ascii=False)
|
||||||
self.send_packet(code, channelPath, data, messageCallback)
|
self.send_packet(code, namespacePath, data, messageCallback)
|
||||||
|
|
||||||
def emit(self, eventName, *eventArguments, **eventKeywords):
|
def emit(self, eventName, *eventArguments, **eventKeywords):
|
||||||
if eventArguments and callable(eventArguments[-1]):
|
if eventArguments and callable(eventArguments[-1]):
|
||||||
|
|
@ -297,9 +319,9 @@ class _SocketIO(object):
|
||||||
eventArguments = eventArguments[:-1]
|
eventArguments = eventArguments[:-1]
|
||||||
else:
|
else:
|
||||||
messageCallback = None
|
messageCallback = None
|
||||||
channelPath = eventKeywords.get('channelPath', '')
|
namespacePath = eventKeywords.get('namespacePath', '')
|
||||||
data = dumps(dict(name=eventName, args=eventArguments), ensure_ascii=False)
|
data = dumps(dict(name=eventName, args=eventArguments), ensure_ascii=False)
|
||||||
self.send_packet(5, channelPath, data, messageCallback)
|
self.send_packet(5, namespacePath, data, messageCallback)
|
||||||
|
|
||||||
def set_messageCallback(self, callback):
|
def set_messageCallback(self, callback):
|
||||||
'Set callback that will be called after receiving an acknowledgment'
|
'Set callback that will be called after receiving an acknowledgment'
|
||||||
|
|
@ -333,18 +355,18 @@ class _SocketIO(object):
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
raise SocketIOPacketError('Received invalid packet (%s)' % packet)
|
raise SocketIOPacketError('Received invalid packet (%s)' % packet)
|
||||||
packetCount = len(packetParts)
|
packetCount = len(packetParts)
|
||||||
code, packetID, channelPath, data = None, None, None, None
|
code, packetID, namespacePath, data = None, None, None, None
|
||||||
if 4 == packetCount:
|
if 4 == packetCount:
|
||||||
code, packetID, channelPath, data = packetParts
|
code, packetID, namespacePath, data = packetParts
|
||||||
elif 3 == packetCount:
|
elif 3 == packetCount:
|
||||||
code, packetID, channelPath = packetParts
|
code, packetID, namespacePath = packetParts
|
||||||
elif 1 == packetCount:
|
elif 1 == packetCount:
|
||||||
code = packetParts[0]
|
code = packetParts[0]
|
||||||
return code, packetID, channelPath, data
|
return code, packetID, namespacePath, data
|
||||||
|
|
||||||
def send_packet(self, code, channelPath='', data='', messageCallback=None):
|
def send_packet(self, code, namespacePath='', data='', messageCallback=None):
|
||||||
callbackNumber = self.set_messageCallback(messageCallback) if messageCallback else ''
|
callbackNumber = self.set_messageCallback(messageCallback) if messageCallback else ''
|
||||||
packetParts = [str(code), callbackNumber, channelPath, data]
|
packetParts = [str(code), callbackNumber, namespacePath, data]
|
||||||
try:
|
try:
|
||||||
self.connection.send(':'.join(packetParts))
|
self.connection.send(':'.join(packetParts))
|
||||||
except socket.error:
|
except socket.error:
|
||||||
|
|
@ -355,39 +377,6 @@ class _SocketIO(object):
|
||||||
return self.connection.connected
|
return self.connection.connected
|
||||||
|
|
||||||
|
|
||||||
class Channel(object):
|
|
||||||
|
|
||||||
def __init__(self, _socketIO, Namespace, channelPath):
|
|
||||||
self._socketIO = _socketIO
|
|
||||||
self._namespace = Namespace(_socketIO)
|
|
||||||
self._channelPath = channelPath
|
|
||||||
self._callbackByEvent = {}
|
|
||||||
|
|
||||||
def on(self, eventName, eventCallback):
|
|
||||||
self._callbackByEvent[eventName] = eventCallback
|
|
||||||
|
|
||||||
def message(self, messageData, messageCallback=None):
|
|
||||||
self._socketIO.message(messageData, messageCallback, channelPath=self._channelPath)
|
|
||||||
|
|
||||||
def emit(self, eventName, *eventArguments):
|
|
||||||
self._socketIO.emit(eventName, *eventArguments, channelPath=self._channelPath)
|
|
||||||
|
|
||||||
def get_namespace(self):
|
|
||||||
return self._namespace
|
|
||||||
|
|
||||||
def _get_eventCallback(self, eventName):
|
|
||||||
# Check callbacks defined by on()
|
|
||||||
try:
|
|
||||||
return self._callbackByEvent[eventName]
|
|
||||||
except KeyError:
|
|
||||||
pass
|
|
||||||
# Check callbacks defined explicitly or use on_()
|
|
||||||
eventNamespace = self.get_namespace()
|
|
||||||
callbackName = 'on_' + eventName.replace(' ', '_')
|
|
||||||
defaultCallback = lambda *eventArguments: eventNamespace.on_(eventName, *eventArguments)
|
|
||||||
return getattr(eventNamespace, callbackName, defaultCallback)
|
|
||||||
|
|
||||||
|
|
||||||
class SocketIOError(Exception):
|
class SocketIOError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -46,20 +46,20 @@ class TestSocketIO(TestCase):
|
||||||
sleep(0.1)
|
sleep(0.1)
|
||||||
self.assertEqual(ON_RESPONSE_CALLED, True)
|
self.assertEqual(ON_RESPONSE_CALLED, True)
|
||||||
|
|
||||||
def test_channels(self):
|
def test_namespaces(self):
|
||||||
mainSocket = self.socketIO.define(Namespace)
|
mainNamespace = self.socketIO.define(Namespace)
|
||||||
chatSocket = self.socketIO.define(Namespace, '/chat')
|
chatNamespace = self.socketIO.define(Namespace, '/chat')
|
||||||
newsSocket = self.socketIO.define(Namespace, '/news')
|
newsNamespace = self.socketIO.define(Namespace, '/news')
|
||||||
self.assertNotEqual(mainSocket.get_namespace().payload, PAYLOAD)
|
self.assertNotEqual(mainNamespace.payload, PAYLOAD)
|
||||||
self.assertNotEqual(chatSocket.get_namespace().payload, PAYLOAD)
|
self.assertNotEqual(chatNamespace.payload, PAYLOAD)
|
||||||
self.assertNotEqual(newsSocket.get_namespace().payload, PAYLOAD)
|
self.assertNotEqual(newsNamespace.payload, PAYLOAD)
|
||||||
newsSocket.emit('aaa', PAYLOAD)
|
newsNamespace.emit('aaa', PAYLOAD)
|
||||||
sleep(0.1)
|
sleep(0.1)
|
||||||
self.assertEqual(newsSocket.get_namespace().payload, PAYLOAD)
|
self.assertEqual(newsNamespace.payload, PAYLOAD)
|
||||||
|
|
||||||
def test_channels_with_callback(self):
|
def test_namespaces_with_callback(self):
|
||||||
mainSocket = self.socketIO.get_channel()
|
mainNamespace = self.socketIO.get_namespace()
|
||||||
mainSocket.message(PAYLOAD, on_response)
|
mainNamespace.message(PAYLOAD, on_response)
|
||||||
sleep(0.1)
|
sleep(0.1)
|
||||||
self.assertEqual(ON_RESPONSE_CALLED, True)
|
self.assertEqual(ON_RESPONSE_CALLED, True)
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue