class WSGIServer(_WSGIServer): def initialize_websockets_manager(self): """ Call thos to start the underlying websockets manager. Make sure to call it once your server is created. """ self.manager = WebSocketManager() self.manager.start() def shutdown_request(self, request): """ The base class would close our socket if we didn't override it. """ pass def link_websocket_to_server(self, ws): """ Call this from your WSGI handler when a websocket has been created. """ self.manager.add(ws) def server_close(self): """ Properly initiate closing handshakes on all websockets when the WSGI server terminates. """ if hasattr(self, 'manager'): self.manager.close_all() self.manager.stop() self.manager.join() delattr(self, 'manager') _WSGIServer.server_close(self)
def test_websocket_close_all(self, MockSelectPoller): m = WebSocketManager(poller=MockSelectPoller()) ws = MagicMock() m.add(ws) m.close_all() ws.terminate.assert_call_once_with(1001, 'Server is shutting down')
def test_websocket_close_all(self, MockSelectPoller): m = WebSocketManager(poller=MockSelectPoller()) ws = MagicMock() m.add(ws) m.close_all() ws.close.assert_called_once_with(code=1001, reason='Server is shutting down')
def test_websocket_close_all(self, MockSelectPoller): m = WebSocketManager(poller=MockSelectPoller()) ws = MagicMock() m.add(ws) m.close_all() ws.terminate.assert_call_once_with(1001, 'Server is shutting down')
def test_websocket_close_all(self, MockSelectPoller): m = WebSocketManager(poller=MockSelectPoller()) ws = MagicMock() m.add(ws) m.close_all() ws.close.assert_called_once_with(code=1001, reason='Server is shutting down')
class WebSocketPlugin(plugins.SimplePlugin): def __init__(self, bus): plugins.SimplePlugin.__init__(self, bus) self.manager = WebSocketManager() def start(self): self.bus.log("Starting WebSocket processing") self.bus.subscribe('stop', self.cleanup) self.bus.subscribe('handle-websocket', self.handle) self.bus.subscribe('websocket-broadcast', self.broadcast) self.manager.start() def stop(self): self.bus.log("Terminating WebSocket processing") self.bus.unsubscribe('stop', self.cleanup) self.bus.unsubscribe('handle-websocket', self.handle) self.bus.unsubscribe('websocket-broadcast', self.broadcast) def handle(self, ws_handler, peer_addr): """ Tracks the provided handler. :param ws_handler: websocket handler instance :param peer_addr: remote peer address for tracing purpose """ self.manager.add(ws_handler) def cleanup(self): """ Terminate all connections and clear the pool. Executed when the engine stops. """ self.manager.close_all() self.manager.stop() self.manager.join() def broadcast(self, message, binary=False): """ Broadcasts a message to all connected clients known to the server. :param message: a message suitable to pass to the send() method of the connected handler. :param binary: whether or not the message is a binary one """ self.manager.broadcast(message, binary)
class WebSocketPlugin(plugins.SimplePlugin): def __init__(self, bus): plugins.SimplePlugin.__init__(self, bus) self.manager = WebSocketManager() def start(self): self.bus.log("Starting WebSocket processing") self.bus.subscribe('stop', self.cleanup) self.bus.subscribe('handle-websocket', self.handle) self.bus.subscribe('websocket-broadcast', self.broadcast) self.manager.start() def stop(self): self.bus.log("Terminating WebSocket processing") self.bus.unsubscribe('stop', self.cleanup) self.bus.unsubscribe('handle-websocket', self.handle) self.bus.unsubscribe('websocket-broadcast', self.broadcast) def handle(self, ws_handler, peer_addr): """ Tracks the provided handler. :param ws_handler: websocket handler instance :param peer_addr: remote peer address for tracing purpose """ self.manager.add(ws_handler) def cleanup(self): """ Terminate all connections and clear the pool. Executed when the engine stops. """ self.manager.close_all() self.manager.stop() self.manager.join() def broadcast(self, message, binary=False): """ Broadcasts a message to all connected clients known to the server. :param message: a message suitable to pass to the send() method of the connected handler. :param binary: whether or not the message is a binary one """ self.manager.broadcast(message, binary)
def run(script_options): global logger level = logging.DEBUG if script_options.verbose else logging.INFO logger = configure_logger(level = level) mgr = WebSocketManager() try: mgr.start() clients = [] # Connect for connection_idx in range(script_options.concurrency): client = EchoClient(script_options.url, mgr, script_options.ca, script_options.key, script_options.cert) client.connect() clients.append(client) logger.info("%d clients are connected" % (connection_idx + 1)) # Send msg = getMessage(script_options) if msg: msg = json.write(msg) logger.info("Sending messages (num=%d):\n%s", script_options.num, msg) for client in clients: for _ in range(script_options.num): client.send(msg) time.sleep(SEND_INTERVAL) logger.info("Done sending") # Sleep before disconnecting logger.info("Sleeping for %d s before disconnecting", script_options.interval) time.sleep(script_options.interval) except KeyboardInterrupt: logger.info("Interrupted by user") finally: logger.info("Disconnecting!") mgr.close_all(code = 1000, message = "Client is closing the connection") mgr.stop() mgr.join()
def start_data_collection(conn_info): for (ip, port) in conn_info: ws_url = "ws://{}:{}/geophone".format(ip, port) print("Connecting to '{}'...".format(ws_url)) try: ws = DataReceiver(ws_url) ws.connect() except Exception as e: print("Unable to connect to '{}' (it probably timed out after {}s). Reason: {}".format(ws_url, WS_TIMEOUT, e)) if __name__ == '__main__': try: ws_manager.start() # start_data_collection([('10.0.0.110', 81)]) start_data_collection([('192.168.0.99', 81),('192.168.0.100', 81),('192.168.0.105', 81),('192.168.0.108', 81),('192.168.0.109', 81),('192.168.0.114', 81),('192.168.0.115', 81),('192.168.0.116', 81),('192.168.0.117', 81),('192.168.0.118', 81)]) while True: for ws in ws_manager.websockets.itervalues(): if not ws.terminated: break else: break time.sleep(3) except KeyboardInterrupt: ws_manager.close_all() ws_manager.stop() ws_manager.join()
if __name__ == '__main__': import time Instant_Pending = json.dumps(CreateData()) count = 0 try: m.start() start_time = time.time() for i in user_list: payload = json.dumps({"Type": 7, "Data": i}) print(type(payload)) client = EchoClient(api_url) client.connect() count += 1 logger.info("%s clients are connected" % count) while True: for ws in m.websockets.values(): if not ws.terminated: dur_time = time.time() - start_time print(dur_time) break else: break time.sleep(3) except KeyboardInterrupt: m.close_all() m.stop() m.join()
#PORTFOLIO DISPLAY print("Total Portfolio in USD : ${0:>.4f}".format( total_portfolio_val)) print() print("Next High Alert Text: {}".format(ALERT_PRICE_HIGH)) print("Next Low Alert Text: {}".format(ALERT_PRICE_LOW)) if ALERT_PRICE_HIGH is not -1 and total_val >= ALERT_PRICE_HIGH: sms_client.send_sms( "\nYour portfolio has reached {0}.\nNext high text notification set to: {1}" .format(ALERT_PRICE_HIGH, ALERT_UPDATE_VAL + ALERT_PRICE_HIGH)) ALERT_PRICE_HIGH += ALERT_UPDATE_VAL ALERT_PRICE_LOW += ALERT_UPDATE_VAL elif ALERT_PRICE_LOW is not -1 and abs( total_val - ALERT_PRICE_LOW ) >= (1.2 * ALERT_UPDATE_VAL) and ALERT_PRICE_LOW >= total_val: sms_client.send_sms( "\nYour portfolio has dropped to {0}.\nNext low text notification set to: {1}" .format(ALERT_PRICE_LOW, ALERT_PRICE_LOW - ALERT_UPDATE_VAL)) ALERT_PRICE_HIGH -= ALERT_UPDATE_VAL ALERT_PRICE_LOW -= ALERT_UPDATE_VAL time.sleep(1) except KeyboardInterrupt: MANAGER.close_all() MANAGER.stop() MANAGER.join()
for pin in pins: gpio.pinMode(pin, gpio.OUTPUT) gpio.digitalWrite(pin,int(pins[pin])) def tempread(pin): value = analog_read(pin) tempr = (value * 3.3)/4096*100 return tempr if __name__ == '__main__': import time try: m.start() client = EchoClient('ws://tairy.me:8888/ws') client.connect() sendmes = {"userid":userid} while True: for ws in m.websockets.itervalues(): if not ws.terminated: sendmes["data"] = {"temp":tempread(2)} ws.send(json.JSONEncoder().encode(sendmes)) break else: break time.sleep(3) except KeyboardInterrupt: m.close_all() m.stop() m.join()