def main(): from ws4py import configure_logger configure_logger(level=logging.DEBUG) parser = argparse.ArgumentParser(description='OpenDerby CherryPy Server') parser.add_argument('--host', default='0.0.0.0') parser.add_argument('-p', '--port', default=9000, type=int) parser.add_argument('--ssl', action='store_true') args = parser.parse_args() cherrypy.config.update({ 'server.socket_host': args.host, 'server.socket_port': args.port, 'tools.staticdir.root': os.path.abspath(os.path.join(os.path.dirname(__file__), 'static')) }) if args.ssl: cherrypy.config.update({ 'server.ssl_certificate': './server.crt', 'server.ssl_private_key': './server.key' }) # Setup WebSockets for the scoreboard WebSocketPlugin(cherrypy.engine).subscribe() cherrypy.tools.websocket = WebSocketTool() # Database setup SAEnginePlugin(cherrypy.engine).subscribe() cherrypy.tools.db = SATool() cherrypy.tree.mount(Derby(args.host, args.port, args.ssl), '', config={ '/': { 'tools.db.on': True, 'tools.caching.on': False, }, '/ws': { 'tools.websocket.on': True, 'tools.websocket.handler_cls': WebSocketHandler }, '/js': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'js' } }) # Use Flask for the Admin from openderby.registration import app from openderby import models cherrypy.tree.graft(app, '/registration') # Start up CherryPy cherrypy.engine.start() cherrypy.engine.block()
def test_level(self): logger = configure_logger(stdout=True, filepath='./my.log', level=logging.DEBUG) self.assertEqual(logger.getEffectiveLevel(), logging.DEBUG) for handler in logger.handlers: self.assertEqual(handler.level, logging.DEBUG)
def init_default(): global Cs_High global Cs_Low Cs_High = 6000 Cs_Low = 50 logger = configure_logger(level=logging.INFO) logging.basicConfig()
def test_level(self): logger = configure_logger(stdout=True, filepath=self.LOG_FILE, level=logging.DEBUG) self.assertEqual(logger.getEffectiveLevel(), logging.DEBUG) for handler in logger.handlers: self.assertEqual(handler.level, logging.DEBUG)
def main(): import argparse from ws4py import configure_logger configure_logger() parser = argparse.ArgumentParser(description='Twister Server') parser.add_argument('--host', default='127.0.0.1') parser.add_argument('-p', '--port', default=9000, type=int) args = parser.parse_args() server = WSGIServer((args.host, args.port), WebSocketWSGIApplication(handler_cls=Twister)) print "Twister running on %s:%s" % (args.host, args.port) server.serve_forever()
def test_stdout_logger(self): logger = configure_logger() for handler in logger.handlers: if isinstance(handler, logging.StreamHandler) and not\ isinstance(handler, handlers.RotatingFileHandler): self.assertTrue(handler.stream is sys.stdout) break else: self.fail("Stream logger not configured")
def test_file_logger(self): filepath = os.path.abspath('./my.log') logger = configure_logger(stdout=False, filepath=filepath) for handler in logger.handlers: if isinstance(handler, handlers.RotatingFileHandler): self.assertEqual(handler.baseFilename, filepath) self.assertEqual(handler.stream.name, filepath) break else: self.fail("File logger not configured")
def run(self): g.logger.debug('YMK in wstundServertApp run') # ## fro cherrypy configure_logger(level=logging.DEBUG) cherrypy.config.update({'server.socket_host': self.host, 'server.socket_port': self.port, 'tools.staticdir.root': os.path.abspath(os.path.join(os.path.dirname(__file__), 'static'))}) WebSocketPlugin(cherrypy.engine).subscribe() cherrypy.tools.websocket = WebSocketTool() cherrypy.quickstart(Root(self.host, self.port), '', config={ '/ws': { 'tools.websocket.on': True, 'tools.websocket.handler_cls': TunWebSocketHandler }, '/js': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'js' } })
def __init__(self, host, port): register("ws4py", WebSocketChaussette) logger = configure_logger() self.server = make_server( app=WebSocketWSGIApplication(handler_cls=WebSocketGevent), host=host, port=port, backend="ws4py", address_family=socket.AF_INET, logger=logger) self.server.serve_forever()
def __init__(self, host, port): register("ws4py", WebSocketChaussette) logger = configure_logger() self.server = make_server( app=WebSocketWSGIApplication(handler_cls=WebSocketGevent), host=host, port=port, backend="ws4py", address_family=socket.AF_INET, logger=logger ) self.server.serve_forever()
def setupServer(): import logging, os from ws4py import configure_logger configure_logger(level=logging.DEBUG) cherrypy.config.update({ 'server.socket_host': "127.0.0.1", 'server.socket_port': 9000, }) config = { '/ws': { 'tools.websocket.on': True, 'tools.websocket.handler_cls': app.ChatWebSocketHandler, 'tools.websocket.protocols': ['toto', 'mytest', 'hithere'] } } app.ChatPlugin(cherrypy.engine).subscribe() cherrypy.tools.websocket = app.WebSocketTool() app_root = app.Root("127.0.0.1", 9000, None) cherrypy.tree.mount(app_root, '/', config) cherrypy.engine.start()
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()
break class StockWS(WebSocketBaseClient): def handshake_ok(self): m.add(self) def received_message(self, msg): # print str(msg) process(msg, "bulldozers.csv") ##inheritancy chain is WebSocketManager -> WebSocketBaseClient -> WebSocket logger = configure_logger() hdlr = logging.FileHandler('sf.log') logger.addHandler(hdlr) trades = 0 balances = {} orders = [] j = [] a = start_level('making_amends') timeout_start = time.time() m = StockManager(start=timeout_start) m.daemon = True m.start() get_accounts(a['level_venue'], a['level_account'], a['level_stock'], 1, 1000) # m.run() # status = Stockfighter.check_level(a['instanceId']) m.join()
#!/usr/bin/env python2 import sys port = int(sys.argv[1]) from gevent import monkey monkey.patch_all() from ws4py.websocket import EchoWebSocket from ws4py.server.geventserver import WSGIServer from ws4py.server.wsgiutils import WebSocketWSGIApplication import logging from ws4py import configure_logger try: logger = logging.getLogger('ws4py') configure_logger(level=10) server = WSGIServer(('0.0.0.0', port), WebSocketWSGIApplication(handler_cls=EchoWebSocket)) print("=====START 0.0.0.0:{}=====".format(port)) server.serve_forever() except KeyboardInterrupt: print("=====STOP 0.0.0.0:{}=====".format(port))
def test_named_logger(self): logger = configure_logger(stdout=False, filepath='./my.log') logger = logging.getLogger('ws4py') self.assertEqual(logger.getEffectiveLevel(), logging.INFO)
''' msg = request.get_json() msg = json.dumps(msg) ws_app.broadcast(msg) return '' @app.route("/") def index(): '''Return the index to the UI Returns: html: The HTML for the app''' return app.send_static_file('index.html') if __name__ == "__main__": # Set up the Root Logger rootLogger = logging.getLogger() rootLogger.setLevel(logging.DEBUG) log.info('Starting the demo application') configure_logger(True, './ws4py.log', logging.DEBUG) # Start the Websocket Server ws_app.start() # Run! # app.debug=1 app.run(host='0.0.0.0', port=app_port)
class WSGIServer(_WSGIServer): handler_class = WebSocketWSGIHandler def __init__(self, *args, **kwargs): """ WSGI server that simply tracks websockets and send them a proper closing handshake when the server terminates. Other than that, the server is the same as its :class:`gevent.pywsgi.WSGIServer` base. """ _WSGIServer.__init__(self, *args, **kwargs) self.pool = GEventWebSocketPool() def stop(self, *args, **kwargs): self.pool.clear() _WSGIServer.stop(self, *args, **kwargs) if __name__ == '__main__': import os from ws4py import configure_logger configure_logger() from ws4py.websocket import EchoWebSocket server = WSGIServer(('127.0.0.1', 9000), WebSocketWSGIApplication(handler_cls=EchoWebSocket)) server.serve_forever()
@cherrypy.expose def getserviceid(self): ret = {"code": 0, "serviceid": "serviceid_23243729472"} return json.dumps(ret) @cherrypy.expose def ws(self): cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler)) if __name__ == "__main__": import logging from ws4py import configure_logger configure_logger(level=logging.DEBUG) parser = argparse.ArgumentParser(description="File CherryPy Server") parser.add_argument("--host", default="127.0.0.1") parser.add_argument("-p", "--port", default=9000, type=int) parser.add_argument("--ssl", action="store_true") args = parser.parse_args() cherrypy.config.update( { "server.socket_host": args.host, "server.socket_port": args.port, "tools.staticdir.root": os.path.abspath(os.path.join(os.path.dirname(__file__), "static")), } )
from ws4py import configure_logger from ws4py.websocket import WebSocket from ws4py.messaging import Message, TextMessage logger = configure_logger(stdout=True) class DataSource(object): def __init__(self): self.frames = set() self.frame = None self.remaining_bytes = None def setblocking(self, flag): pass def feed(self, message): if isinstance(message, Message): message = message.single(mask=True) else: message = TextMessage(message).single(mask=True) self.frames.add(message) def recv(self, size): if not self.frame: if not self.frames: return b'' self.frame = self.frames.pop() self.remaining_bytes = self.frame current_bytes = self.remaining_bytes[:size] self.remaining_bytes = self.remaining_bytes[size:]
# Copyright (c) 2020 by xfangfang. All Rights Reserved. import logging from ws4py import configure_logger logger = configure_logger(stdout=True, level=logging.INFO, filepath='car.log') # 电机GPIO引脚 L1 = 12 L2 = 16 R1 = 20 R2 = 21 ## 二进制数用来翻转电机 当电机接线接反时无需重新接线 修改此值即可 INIT = int('01', 2) # 两个舵机端口号 # 水平舵机 PIN_SERVO_H = 14 # 垂直舵机 PIN_SERVO_V = 15 # 服务端口号 PORT = 6082 # 视频设置 WIDTH = 640 HEIGHT = 480 # FPS FRAMERATE = 30 # 是否翻转视频 VFLIP = False
<br /> <label for='message'>%(username)s: </label><input type='text' id='message' /> <input id='send' type='submit' value='Send' /> </form> </body> </html> """ % {'username': "******" % random.randint(0, 100), 'host': self.host, 'port': self.port, 'scheme': self.scheme} @cherrypy.expose def ws(self): cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler)) if __name__ == '__main__': import logging from ws4py import configure_logger configure_logger(level=logging.DEBUG) parser = argparse.ArgumentParser(description='Echo CherryPy Server') parser.add_argument('--host', default='127.0.0.1') parser.add_argument('-p', '--port', default=9000, type=int) parser.add_argument('--ssl', action='store_true') args = parser.parse_args() cherrypy.config.update({'server.socket_host': args.host, 'server.socket_port': args.port, 'tools.staticdir.root': os.path.abspath(os.path.join(os.path.dirname(__file__), 'static'))}) if args.ssl: cherrypy.config.update({'server.ssl_certificate': './server.crt', 'server.ssl_private_key': './server.key'})
""" Sets up websockets for Dashboard """ # pylint: disable-msg=C0103 import json import os from ws4py.client import WebSocketBaseClient from ws4py.manager import WebSocketManager from ws4py import format_addresses, configure_logger import queue import requests LOGGER = configure_logger() MANAGER = WebSocketManager() coin_queue = queue.Queue() #FIXME: Change these global to local variable BTC_USD = 0.0 XRB_BTC = 0.0 STORM_USD = 0.0 class SetQueue(): """ Custom Queue that uses a set instead of a regular queue. This keeps a set of coin names as well as a dict of it's coin:value :param queue.Queue: """ def __init__(self): self.queue = set() self.values = dict({})
from ws4py.client.threadedclient import WebSocketClient from ws4py import format_addresses, configure_logger import json import time import thread import argparse logger = configure_logger() parser = argparse.ArgumentParser(description='client for qq') parser.add_argument('-host', action="store", dest="host", default="localhost") parser.add_argument('-port', action="store", dest="port", default=9000) parser.add_argument('-username', action="store", dest="username") parser.add_argument('-give', action="store", dest="give") parser.add_argument('-search', action="store", dest="search") args = parser.parse_args() class DummyClient(WebSocketClient): def opened(self): logger.info("cool.") self.is_connected = True self.state = "wait" thread.start_new_thread(self.state_machine, ()) def cls(self): print(chr(27) + "[2J") def send(self, msg): super(DummyClient, self).send(json.dumps(msg)) def state_machine(self):
from ws4py import configure_logger from ws4py.websocket import WebSocket from ws4py.messaging import Message, TextMessage logger = configure_logger(stdout=True) class DataSource(object): def __init__(self): self.frames = set() self.frame = None self.remaining_bytes = None def setblocking(self, flag): pass def feed(self, message): if isinstance(message, Message): message = message.single(mask=True) else: message = TextMessage(message).single(mask=True) self.frames.add(message) def recv(self, size): if not self.frame: if not self.frames: return b'' self.frame = self.frames.pop() self.remaining_bytes = self.frame current_bytes = self.remaining_bytes[:size]
N/A ''' msg = request.get_json() msg = json.dumps(msg) ws_app.broadcast(msg) return '' @app.route("/") def index(): '''Return the index to the UI Returns: html: The HTML for the app''' return app.send_static_file('index.html') if __name__ == "__main__": # Set up the Root Logger rootLogger = logging.getLogger() rootLogger.setLevel(logging.DEBUG) log.info('Starting the demo application') configure_logger(True, './ws4py.log', logging.DEBUG); # Start the Websocket Server ws_app.start() # Run! # app.debug=1 app.run(host='0.0.0.0', port=app_port)
from gevent import monkey monkey.patch_all() import argparse import time import gevent from ws4py.client import WebSocketBaseClient from ws4py import configure_logger logger = configure_logger(level='WARNING') stats = {} # TODO: check that other clients from the same channel received the message class WebSocketClient(WebSocketBaseClient): def __init__(self, client_id, url, *args, **kwargs): self.client_id = client_id self.stats = stats.setdefault(self.client_id, {}) self.errors = self.stats.setdefault('errors', {}) self.message_count = 0 super(WebSocketClient, self).__init__(url, *args, **kwargs) def get_new_message(self): self.message_count += 1 return 'Message #{:<3} from client #{:<5}'.format( self.message_count, self.client_id) def connect(self): self.stats['handshake_started_at'] = time.time() return super(WebSocketClient, self).connect()