import threading, Queue
from amitu import websocket_client
class _Writer(threading.Thread):
def __init__(self, ws):
super(_Writer, self).__init__()
self.daemon = True
self.ws = ws
self.queue = Queue.Queue()
def send(self, data):
self.queue.put(data)
def run(self):
while True:
self.ws._send(self.queue.get(block=True))
class WebSocket(websocket_client.WebSocket):
"""
Threaded WebSocket class
Use this class to use a threaded websocket. It reads data from server
on the current thread, and sends data on a separate daemon thread.
>>> def onmessage(message): print "onmessage", message
...
>>> def onopen(): print "onopen"
...
>>> def onclose(): print "onclose"
...
>>> ws = WebSocket("ws://server.com:8080/path")
>>> ws.onopen(onopen)
>>> ws.onclose(onclose)
>>> ws.onmessage(onmessage)
>>> ws.run() # blocks
"""
def __init__(self, *args, **kw):
websocket_client.WebSocket.__init__(self, *args, **kw)
self.writer = _Writer(self)
self.onopen_handlers = []
self.onclose_handlers = []
self.onmessage_handlers = []
def run(self):
self.writer.start()
websocket_client.WebSocket.run(self)
def send(self, data):
self.writer.send(data)
def _fire_onopen(self):
for cb in self.onopen_handlers: cb()
def _fire_onmessage(self, data):
for cb in self.onmessage_handlers: cb(data)
def _fire_onclose(self):
for cb in self.onclose_handlers: cb()
def onopen(self, cb): self.onopen_handlers.append(cb)
def onmessage(self, cb): self.onmessage_handlers.append(cb)
def onclose(self, cb): self.onclose_handlers.append(cb)
class WebSocketThreaded(WebSocket, threading.Thread):
"""
WebSocketThreaded
This is a thread that runs in the background, reading and writing both
in two different threads.
>>> def onmessage(message): print "onmessage", message
...
>>> def onopen(): print "onopen"
...
>>> def onclose(): print "onclose"
...
>>> ws = WebSocketThreaded("ws://server.com:8080/path")
>>> ws.onopen(onopen)
>>> ws.onclose(onclose)
>>> ws.onmessage(onmessage)
>>> ws.start()
>>> ws.wait()
"""
def __init__(self, *args, **kw):
WebSocket.__init__(self, *args, **kw)
threading.Thread.__init__(self)
import pytest
from unittest.mock import Mock
import sys
# insert at 1, 0 is the script path (or '' in REPL)
if not '../event-notifier' in sys.path:
sys.path.insert(1, '../event-notifier')
from EventNotifier.SubscriberManager import SubscriberManager
class TestExamples:
def test_subscribe_to_all(self):
from EventNotifier import Notifier
class CallableFileWatchdog:
def __init__(self, pathToWatch):
self.pathToWatch = pathToWatch
def __call__(self, *args, **kwargs):
if len(args) > 0:
print \
(f"Event {args[0]} at path {self.pathToWatch} is called with following simple args: {[*args]} and with following keyword args: { {**kwargs} }")
callable_watchog = CallableFileWatchdog("some\\path\\here")
notifier = Notifier(["onCreate", "onOpen", "onModify", "onClose", "onDelete"])
notifier.subscribe_to_all(callable_watchog)
notifier.raise_event("onCreate", "onCreate", fileName="test_file.txt")
notifier.raise_event("onOpen", "onOpen", openMode="w+", fileName="test_file.txt")
def test_get_registered_events(self):
from EventNotifier import Notifier
notifier = Notifier(["onCreate", "onOpen", "onModify", "onClose", "onDelete"])
print(notifier.get_registered_events())
def test_remove_subscribers_by_event_name(self):
from EventNotifier import Notifier
class FileWatchDog():
def onOpen(self, fileName, openMode):
print(f"File {fileName} opened with {openMode} mode")
def onClose(self, fileName):
print(f"File {fileName} closed")
def onOpenStandaloneMethod(fileName, openMode):
print(f"StandaloneMethod: File {fileName} opened with {openMode} mode")
watchDog = FileWatchDog()
notifier = Notifier(["onCreate", "onOpen", "onModify", "onClose", "onDelete"])
notifier.subscribe("onOpen", watchDog.onOpen)
notifier.subscribe("onOpen", onOpenStandaloneMethod)
notifier.subscribe("onClose", watchDog.onClose)
print("\nAfter subscription:")
notifier.raise_event("onOpen", openMode="w+", fileName="test_file.txt")
notifier.raise_event("onClose", fileName="test_file.txt")
notifier.remove_subscribers_by_event_name("onOpen")
print("\nAfter removal of onOpen subscribers:")
notifier.raise_event("onOpen", openMode="w+", fileName="test_file.txt")
notifier.raise_event("onClose", fileName="test_file.txt")
notifier.remove_subscribers_by_event_name("onClose")
print("\nAfter removal of onClose subscribers:")
notifier.raise_event("onOpen", openMode="w+", fileName="test_file.txt")
notifier.raise_event("onClose", fileName="test_file.txt")
def test_remove_all_subscribers(self):
from EventNotifier import Notifier
class FileWatchDog():
def onOpen(self, fileName, openMode):
print(f"File {fileName} opened with {openMode} mode")
def onClose(self, fileName):
print(f"File {fileName} closed")
def onOpenStandaloneMethod(fileName, openMode):
print(f"StandaloneMethod: File {fileName} opened with {openMode} mode")
watchDog = FileWatchDog()
notifier = Notifier(["onCreate", "onOpen", "onModify", "onClose", "onDelete"])
notifier.subscribe("onOpen", watchDog.onOpen)
notifier.subscribe("onOpen", onOpenStandaloneMethod)
notifier.subscribe("onClose", watchDog.onClose)
print("\nAfter subscription:")
notifier.raise_event("onOpen", openMode="w+", fileName="test_file.txt")
notifier.raise_event("onClose", fileName="test_file.txt")
notifier.remove_all_subscribers()
print("\nAfter removal of all subscribers:")
notifier.raise_event("onOpen", openMode="w+", fileName="test_file.txt")
notifier.raise_event("onClose", fileName="test_file.txt")
from websocket import *
import websocket, httplib
'''
connect to the socketio server
1. perform the HTTP handshake
2. open a websocket connection
'''
def connect(self) :
conn = httplib.HTTPConnection('localhost:8124')
conn.request('POST','/socket.io/1/')
resp = conn.getresponse()
hskey = resp.read().split(':')[0]
self._ws = websocket.WebSocket(
'ws://localhost:8124/socket.io/1/websocket/'+hskey,
onopen = self._onopen,
onmessage = self._onmessage)
def my_msg_handler(msg):
print 'Got "%s"!' % msg
def encode_for_socketio(message):
"""
Encode 'message' string or dictionary to be able
to be transported via a Python WebSocket client to
a Socket.IO server (which is capable of receiving
WebSocket communications). This method taken from
gevent-socketio.
"""
MSG_FRAME = "~m~"
HEARTBEAT_FRAME = "~h~"
JSON_FRAME = "~j~"
if isinstance(message, basestring):
encoded_msg = message
elif isinstance(message, (object, dict)):
return encode_for_socketio(JSON_FRAME + json.dumps(message))
else:
raise ValueError("Can't encode message.")
return MSG_FRAME + str(len(encoded_msg)) + MSG_FRAME + encoded_msg
# socket = websocket.WebSocket('ws://localhost:5000/', onmessage=my_msg_handler)
# self._ws = websocket.WebSocket(
# 'ws://localhost:8124/socket.io/1/websocket/'+hskey,
# onopen = self._onopen,
# onmessage = self._onmessage)
conn = httplib.HTTPConnection('localhost:5000')
conn.request('POST','/socket.io/1/')
resp = conn.getresponse()
respdata = resp.read()
hskey = respdata.split(':')[0]
print respdata
print hskey
socket = websocket.WebSocket('ws://localhost:5000/socket.io/1/websocket/'+hskey, onmessage=my_msg_handler)
# # socket.onopen = lambda: socket.send(encode_for_socketio('Hello world!'))
senddata = '5:::{"message":"hi"}'
socket.onopen = lambda: socket.send(senddata)
# ws = websocket.create_connection('ws://localhost:5000/data')
# msg = "Hello, world!"
# msg = encode_for_socketio(msg)
# ws.send(msg)
try:
asyncore.loop()
except KeyboardInterrupt:
socket.close()