示例#1
0
class Server(Singleton):
	STARTED = "server_started"
	STOPPED = "server_stopped"
	def __init__(self, settings):
		self.settings = settings
		if "events" in self.settings:
			self.eventer = Eventer(self.settings["events"])
		else:
			self.eventer = Eventer()
		self.init_controllers_mapping()

	def start(self):
		wsgi_app = Router(self)
		wsgi_app = SharedDataMiddleware(wsgi_app, {
			'/': self.settings["files"]
		})
		self.server = None
		if "ssl" in self.settings:
			ssl_info = self.settings["ssl"]
			if "key" in ssl_info and "cert" in ssl_info:
				self.server = WebSocketServer((self.settings["application"]["address"], self.settings["application"]["port"]),
					wsgi_app, keyfile=ssl_info["key"], certfile=ssl_info["cert"])
		if not self.server:
			self.server = WebSocketServer((self.settings["application"]["address"], self.settings["application"]["port"]), wsgi_app)
		gevent.signal(signal.SIGTERM, self.stop)
		gevent.signal(signal.SIGINT, self.stop)
		self.eventer.publish(Server.STARTED, self)
		try:
			self.server.serve_forever()
		except Exception, e:
			logger.error("start server error %s", str(e), exc_info=True)
示例#2
0
def run_web_servers(port):
    resource = Resource(
        OrderedDict([('/ws', ClientConnection), ('.*', static_file_server)]))

    server = WebSocketServer(("", port), resource, debug=False)
    print "Now listening on port %d" % port
    server.serve_forever()
示例#3
0
def start():
    print("Starting pycaserver.")
    #host = "127.0.0.1"
    #host = "10.6.100.199"
    host = "0.0.0.0"
    port = 8888
    server = WebSocketServer((host, port), wsgi_app)
    server.serve_forever()
示例#4
0
文件: dealer.py 项目: Jesus89/rainbow
 def run_forever(self, host='0.0.0.0', debug=False):
     try:
         dealer_server = WebSocketServer(
             (host, 8080),
             Resource(OrderedDict({'/': DealerApplication})),
             debug=debug)
         dealer_server.serve_forever()
     except KeyboardInterrupt:
         dealer_server.close()
         raise KeyboardInterrupt
示例#5
0
 def websocket():
     """
     Run websocket flask application, SSL handled by nginx
     """
     http_server_ws = WebSocketServer(
         ('127.0.0.1',
          8890),
         Resource(OrderedDict([('/websocket/', HandlerWS)]))
     )
     http_server_ws.serve_forever()
示例#6
0
def init():
    from settings import config
    host = config.get('restAPI', 'host', fallback='0.0.0.0')
    port = config.getint('restAPI', 'port', fallback=5000)
    debug = config.getboolean('restAPI', 'debug', fallback=False)
    app.debug = debug

    global server
    server = WebSocketServer((host, port), app, handler_class=WebSocketHandler)
    server.serve_forever()
示例#7
0
    def startServer(self):
        """Starts the server"""

        if not self.certfile:
            server = WebSocketServer((self.host, self.port), self.handleClient)
        else:
            server = WebSocketServer((self.host, self.port), self.handleClient,
                                     self.certfile)

        server.serve_forever()
示例#8
0
 def run_forever(self, host='0.0.0.0', debug=False):
     try:
         dealer_server = WebSocketServer(
             (host, 8080),
             Resource(OrderedDict({'/': DealerApplication})),
             debug=debug)
         dealer_server.serve_forever()
     except KeyboardInterrupt:
         dealer_server.close()
         raise KeyboardInterrupt
示例#9
0
def run_web_servers(port):
    resource = Resource(
        OrderedDict([
            ('/ws', ClientConnection),
            ('.*', static_file_server)
        ])
    )

    server = WebSocketServer(("", port), resource, debug=False)
    print "Now listening on port %d" % port
    server.serve_forever()
示例#10
0
def main():
    args = parse_args()
    async_mode = 'gevent'  # eventlet, gevent_uwsgi, gevent, threading

    logger.info('Running automate version {}', Env.version)
    from utils.io import delete_old_files
    delete_old_files(Env.tmp)

    # -------------------------------------------------------------------------

    if args.debug:
        async_mode = 'threading'
        Env.debug_mode = True
    else:
        from gevent import monkey
        monkey.patch_all()

    # -------------------------------------------------------------------------

    from flask_socketio import SocketIO
    import flask
    from www import app

    # -------------------------------------------------------------------------

    socketio = SocketIO(app,
                        json=flask.json,
                        async_mode=async_mode,
                        ping_interval=100 * 1000)
    register_routes(app, socketio)

    # -------------------------------------------------------------------------

    if args.backdoor:
        from www import backdoor
        backdoor.register_routes(app, socketio)

    # -------------------------------------------------------------------------

    logger.info('Listening on {host}:{port} (debug={debug})', **vars(args))
    Env.dump_info('Configuration in env.py')
    logger.info('removing old files from {}', Env.tmp)

    # -------------------------------------------------------------------------

    if args.debug:
        app.run(debug=args.debug, host=args.host, port=args.port)
    else:
        from geventwebsocket import WebSocketServer
        http_server = WebSocketServer((args.host, args.port), app)
        http_server.serve_forever()

    return app, args
示例#11
0
def main():
    ""
    host = config.get("HOSTDIVULGER")
    port = config.get("PORTDIVULGER")

    print(u"serving on {host}:{port}".format(**locals()))

    server = WebSocketServer(
        (host, port),
        Resource(OrderedDict({
            "^/divulge/.+/": DivulgeApplication,
        })),
        debug=False,
    )
    server.serve_forever()
示例#12
0
class ServerTransportWS(ServerTransport):
    def __init__(self, scheme, parsed_uri, apps=None, kwargs=None):
        super(ServerTransportWS, self).__init__()

        assert scheme == 'ws'
        self.wss = None
        self.address = parsed_uri.hostname
        self.port = parsed_uri.port
        self.apps = apps or {}
        self.apps[parsed_uri.path] = ServerApplication
        self.kwargs = kwargs or {}

    def serve_forever(self, server):
        self.wss = WebSocketServer((self.address, self.port),
                                   ServerResource(self.apps, server),
                                   **self.kwargs)

        self.wss.serve_forever()
示例#13
0
class ServerTransportWS(ServerTransport):
    def __init__(self, scheme, parsed_uri, apps=None, kwargs=None):
        super(ServerTransportWS, self).__init__()

        assert scheme == 'ws'
        self.wss = None
        self.address = parsed_uri.hostname
        self.port = parsed_uri.port
        self.apps = apps or {}
        self.apps[parsed_uri.path] = ServerApplication
        self.kwargs = kwargs or {}

    def serve_forever(self, server):
        self.wss = WebSocketServer(
            (self.address, self.port),
            ServerResource(self.apps, server),
            **self.kwargs
        )

        self.wss.serve_forever()
示例#14
0
def gevent_websocket_server(port, path='/'):
    from geventwebsocket import WebSocketServer, WebSocketApplication, Resource

    class WebSocketRPCApplication(WebSocketApplication):
        def on_open(self):
            log.debug('conn open: %s %s', args, kwargs)

        def on_message(self, message):
            try:
                ret = server_call(message, self.ws.send)
                log.info('ret=%s', ret)
                if isinstance(ret, str):
                    self.ws.send(ret)
            except:
                log.info(traceback.format_exc())

        def on_close(self, reason):
            log.debug('conn close: %s', reason)

    srv = WebSocketServer(('0.0.0.0', port), Resource({path: MyApplication}))
    log.info('server started at:%d', port)
    srv.serve_forever()
    log.warn("stopped")
示例#15
0
def main():

    opt = process_command_line()
    print opt

    zmq_ctx = zmq.Context()

    resources = OrderedDict()
    resources['^/websocket'] = WSApplication
    resources['^/.*'] = app
    server = WebSocketServer(('0.0.0.0', opt.port), Resource(resources))

    def shutdown():

        print("\nShutting down...")

        server.stop()
        zmq_ctx.destroy()
        sys.exit()

    gevent.signal(signal.SIGINT, shutdown)
    gevent.signal(signal.SIGTERM, shutdown)

    server.serve_forever()
示例#16
0
def main():
    xmas = WebSocketServer(
        ('0.0.0.0', 8000),
        Resource(
            OrderedDict([('/xmas', client.ClientImpl),
                         ('/interface', interface.InterfaceImpl)])))

    application_state = State()
    application_gui = gui.GuiImpl(application_state,
                                  santa.GaOptimizingSanta(application_state))
    """ So that interface can update the packages aswell. """
    application_state.add_package = application_gui.add_package
    """ Make state reachable throughout all applications """
    xmas.state = application_state

    try:
        application_gui.start()
        xmas.start()
        xmas.serve_forever()
    except KeyboardInterrupt:
        pass

    application_state.clean()
    application_gui.stop()
示例#17
0
# -*- coding: utf-8 -*-
"""gevent websocket server"""

# https://github.com/gf0842wf/gevent-websocket

from geventwebsocket import WebSocketServer, WebSocketApplication, Resource


class EchoApplication(WebSocketApplication):
    def on_open(self):
        print "Connection opened"

    def on_message(self, message):
        self.ws.send(message)

    def on_close(self, reason):
        print reason


if __name__ == "__main__":
    wss = WebSocketServer(('', 8201), Resource({'/chat': EchoApplication}))
    wss.serve_forever()
def app_worker(app, port):
    server = WebSocketServer(('', port), app)
    server.serve_forever()
示例#19
0
        """
        mon = get_monitor()
        while True:
            self.ws.send("%.1f %.1f %.1f %.1f %.1f" %
                         (mon.CO2, mon.temp, mon.hum, mon.eCO2, mon.TVOC))
            gevent.sleep(0.05)

    def on_close(self, reason):
        """
        On socket close callback
        """
        print("Connection closed", reason)

def get_html(_, start_response):
    """
    Get HTML for browser
    """
    start_response("200 OK", [("Content-Type", "text/html")])
    return [bytes(line, "utf-8") 
            for line in open("air_quality_monitor/static/monitor.html").readlines()]

resource = Resource([
    ('/', get_html),
    ('/data', Application)
])

if __name__ == "__main__":
    server = WebSocketServer(('', 8000), resource, debug=True)
    print("Server started")
    server.serve_forever()
示例#20
0
文件: start.py 项目: janhybs/automate
    logger.info('Configuration in env.py:\n{}', info)

    return app


def wsgi(*args, **kwargs):
    return create_app()(*args, **kwargs)


if __name__ == '__main__':
    app = create_app()
    from geventwebsocket import WebSocketServer

    # from gevent.pywsgi import WSGIServer
    http_server = WebSocketServer(('', 5000), app)
    http_server.serve_forever()



# app.run(debug=args.debug, host=args.host, port=args.port)
#



#
#
# import json
# import pathlib
# from flask import Flask, send_file
# from PIL import Image, ImageDraw, ImageFont
# import urllib.request
示例#21
0
class PytoWebSocketServer(HAInterface):
    _api = PytomationAPI()

    def __init__(self, *args, **kwargs):
        self._address = kwargs.get('address', config.http_address)
        self._port = kwargs.get('port', int(config.http_port))
        self._path = kwargs.get('path', config.http_path)
        super(PytoWebSocketServer, self).__init__(self._address, *args, **kwargs)
        self.unrestricted = True  # To override light object restrictions

    def _init(self, *args, **kwargs):
        self._ssl_path = None
        self.ws = None
        try:
            self._ssl_path = config.ssl_path
        except:
            pass
        super(PytoWebSocketServer, self)._init(*args, **kwargs)

    def run(self):
        resource = collections.OrderedDict()
        resource['/api/bridge'] = PytoWebSocketApp
        resource['/api/device*'] = self.api_app
        resource['/api/voice'] = self.api_app
        resource['/'] = self.http_file_app
        if self._ssl_path:            
            self.ws = WebSocketServer(
            (self._address, self._port),
            Resource(resource),
            pre_start_hook=auth_hook, keyfile=self._ssl_path + '/server.key', certfile=self._ssl_path + '/server.crt')
        else:
            self.ws = WebSocketServer(
                (self._address, self._port),
                Resource(resource),
                pre_start_hook=auth_hook)

        print "Serving WebSocket Connection on", self._address, "port", self._port, "..."
        StateDevice.onStateChangedGlobal(self.broadcast_state)
        self.ws.serve_forever()

    def api_app(self, environ, start_response):
        method = environ['REQUEST_METHOD'].lower()
        if method == 'post':
            data = environ['wsgi.input'].read()
        else:
            data = None
        start_response("200 OK", [("Content-Type", "text/html"), ('Access-Control-Allow-Origin', '*')])
        return self._api.get_response(path='/'.join(environ['PATH_INFO'].split('/')[2:]), source=PytoWebSocketServer,
                                      method=method, data=data)

    def http_file_app(self, environ, start_response):
        path_info = environ['PATH_INFO']
        http_file = self._path + path_info
        if self._ssl_path:
            protocol = 'https://'
        else:
            protocol = 'http://'

        if os.path.exists(http_file):
            if os.path.isdir(http_file):
                if http_file.endswith('/'):
                    http_file += 'index.html'
                else:
                    if path_info.startswith('/'):
                        location = protocol + self._address + ':' + str(self._port) + path_info + '/'
                    else:
                        location = protocol + self._address + ':' + str(self._port) + '/' + path_info + '/'
                    start_response("302 Found",
                                   [("Location", location), ('Access-Control-Allow-Origin', '*')])
                    return ''

            mime = mimetypes.guess_type(http_file)
            start_response("200 OK", [("Content-Type", mime[0]), ('Access-Control-Allow-Origin', '*')])
            return open(http_file, "rb")
        else:
            start_response("404 Not Found", [("Content-Type", "text/html"), ('Access-Control-Allow-Origin', '*')])
            return "404 Not Found"

    def broadcast_state(self, state, source, prev, device):
        # TODO: add queue system and separate thread to avoid blocking on long network operations
        if self.ws:
            for client in self.ws.clients.values():
                message = self._api.get_state_changed_message(state, source, prev, device)
                client.ws.send(message)
示例#22
0
def start():
    logger.info("Starting pycaserver.")
    host = "127.0.0.1"
    port = 8888
    server = WebSocketServer((host, port), wsgi_app)
    server.serve_forever()
# -*- coding: utf-8 -*-

"""gevent websocket server"""

# https://github.com/gf0842wf/gevent-websocket

from geventwebsocket import WebSocketServer, WebSocketApplication, Resource


class EchoApplication(WebSocketApplication):
    def on_open(self):
        print "Connection opened"

    def on_message(self, message):
        self.ws.send(message)

    def on_close(self, reason):
        print reason


if __name__ == "__main__":
    wss = WebSocketServer(('', 8201),Resource({'/chat': EchoApplication}))
    wss.serve_forever()
示例#24
0
class PytoWebSocketServer(HAInterface):
    _api = PytomationAPI()

    def __init__(self, *args, **kwargs):
        self._address = kwargs.get("address", config.http_address)
        self._port = kwargs.get("port", int(config.http_port))
        self._path = kwargs.get("path", config.http_path)
        super(PytoWebSocketServer, self).__init__(self._address, *args, **kwargs)
        self.unrestricted = True  # To override light object restrictions
        self.ws = None

    def _init(self, *args, **kwargs):
        self._ssl_path = None
        try:
            self._ssl_path = config.ssl_path
        except:
            pass
        super(PytoWebSocketServer, self)._init(*args, **kwargs)

    def run(self):
        if self._ssl_path:
            self.ws = WebSocketServer(
                (self._address, self._port),
                Resource(
                    {
                        "/api/bridge": PytoWebSocketApp,
                        "/api/device*": self.api_app,
                        "/api/voice": self.api_app,
                        "/": self.http_file_app,
                    }
                ),
                pre_start_hook=auth_hook,
                keyfile=self._ssl_path + "/server.key",
                certfile=self._ssl_path + "/server.crt",
            )
        else:
            self.ws = WebSocketServer(
                (self._address, self._port),
                Resource(
                    {
                        "/api/bridge": PytoWebSocketApp,
                        "/api/device*": self.api_app,
                        "/api/voice": self.api_app,
                        "/": self.http_file_app,
                    }
                ),
                pre_start_hook=auth_hook,
            )

        print "Serving WebSocket Connection on", self._address, "port", self._port, "..."
        StateDevice.onStateChangedGlobal(self.broadcast_state)
        self.ws.serve_forever()

    def api_app(self, environ, start_response):
        method = environ["REQUEST_METHOD"].lower()
        if method == "post":
            data = environ["wsgi.input"].read()
        else:
            data = None
        start_response("200 OK", [("Content-Type", "text/html"), ("Access-Control-Allow-Origin", "*")])
        return self._api.get_response(
            path="/".join(environ["PATH_INFO"].split("/")[2:]), source=PytoWebSocketServer, method=method, data=data
        )

    def http_file_app(self, environ, start_response):
        path_info = environ["PATH_INFO"]
        http_file = self._path + path_info
        if self._ssl_path:
            protocol = "https://"
        else:
            protocol = "http://"

        if os.path.exists(http_file):
            if os.path.isdir(http_file):
                if http_file.endswith("/"):
                    http_file += "index.html"
                else:
                    if path_info.startswith("/"):
                        location = protocol + self._address + ":" + str(self._port) + path_info + "/"
                    else:
                        location = protocol + self._address + ":" + str(self._port) + "/" + path_info + "/"
                    start_response("302 Found", [("Location", location), ("Access-Control-Allow-Origin", "*")])
                    return ""

            mime = mimetypes.guess_type(http_file)
            start_response("200 OK", [("Content-Type", mime[0]), ("Access-Control-Allow-Origin", "*")])
            return open(http_file, "rb")
        else:
            start_response("404 Not Found", [("Content-Type", "text/html"), ("Access-Control-Allow-Origin", "*")])
            return "404 Not Found"

    def broadcast_state(self, state, source, prev, device):
        # TODO: add queue system and separate thread to avoid blocking on long network operations
        if self.ws:
            for client in self.ws.clients.values():
                message = self._api.get_state_changed_message(state, source, prev, device)
                client.ws.send(message)
示例#25
0
def start():
	logger.info("Starting klystronserver.")
	host = "127.0.0.1"
	port = 8889
	server = WebSocketServer((host, port), wsgi_klystron_app)
	server.serve_forever()
示例#26
0
class PytoWebSocketServer(HAInterface):
    _api = PytomationAPI()

    def __init__(self, *args, **kwargs):
        self._address = kwargs.get('address', config.http_address)
        self._port = kwargs.get('port', int(config.http_port))
        self._path = kwargs.get('path', config.http_path)
        super(PytoWebSocketServer, self).__init__(self._address, *args,
                                                  **kwargs)
        self.unrestricted = True  # To override light object restrictions

    def _init(self, *args, **kwargs):
        self._ssl_path = None
        self.ws = None
        try:
            self._ssl_path = config.ssl_path
        except:
            pass
        super(PytoWebSocketServer, self)._init(*args, **kwargs)

    def run(self):
        resource = collections.OrderedDict()
        resource['/api/bridge'] = PytoWebSocketApp
        resource['/api/device*'] = self.api_app
        resource['/api/voice'] = self.api_app
        resource['/'] = self.http_file_app
        if self._ssl_path:
            self.ws = WebSocketServer((self._address, self._port),
                                      Resource(resource),
                                      pre_start_hook=auth_hook,
                                      keyfile=self._ssl_path + '/server.key',
                                      certfile=self._ssl_path + '/server.crt')
        else:
            self.ws = WebSocketServer((self._address, self._port),
                                      Resource(resource),
                                      pre_start_hook=auth_hook)

        print "Serving WebSocket Connection on", self._address, "port", self._port, "..."
        StateDevice.onStateChangedGlobal(self.broadcast_state)
        self.ws.serve_forever()

    def api_app(self, environ, start_response):
        method = environ['REQUEST_METHOD'].lower()
        if method == 'post':
            data = environ['wsgi.input'].read()
        else:
            data = None
        start_response("200 OK", [("Content-Type", "text/html"),
                                  ('Access-Control-Allow-Origin', '*')])
        return self._api.get_response(path='/'.join(
            environ['PATH_INFO'].split('/')[2:]),
                                      source=PytoWebSocketServer,
                                      method=method,
                                      data=data)

    def http_file_app(self, environ, start_response):
        path_info = environ['PATH_INFO']
        http_file = self._path + path_info
        if self._ssl_path:
            protocol = 'https://'
        else:
            protocol = 'http://'

        if os.path.exists(http_file):
            if os.path.isdir(http_file):
                if http_file.endswith('/'):
                    http_file += 'index.html'
                else:
                    if path_info.startswith('/'):
                        location = protocol + self._address + ':' + str(
                            self._port) + path_info + '/'
                    else:
                        location = protocol + self._address + ':' + str(
                            self._port) + '/' + path_info + '/'
                    start_response("302 Found",
                                   [("Location", location),
                                    ('Access-Control-Allow-Origin', '*')])
                    return ''

            mime = mimetypes.guess_type(http_file)
            start_response("200 OK", [("Content-Type", mime[0]),
                                      ('Access-Control-Allow-Origin', '*')])
            return open(http_file, "rb")
        else:
            start_response("404 Not Found",
                           [("Content-Type", "text/html"),
                            ('Access-Control-Allow-Origin', '*')])
            return "404 Not Found"

    def broadcast_state(self, state, source, prev, device):
        # TODO: add queue system and separate thread to avoid blocking on long network operations
        if self.ws:
            for client in self.ws.clients.values():
                message = self._api.get_state_changed_message(
                    state, source, prev, device)
                client.ws.send(message)
示例#27
0
def main():
    """
    ========================================
        Codigo que no se para que sirve
    ========================================
    """

    opt = process_command_line()

    zmq_ctx = zmq.Context()

    # Pasandole el contexto del mensajero, y el nombre de la camara
    came_0 = CameraLink(zmq_ctx, 'cam0')
    came_0.connect(opt.camera_server_address)
    # Si hay mas camaras, se deben seguir asociando con este formato
    camaras = {'cam0': came_0}
    # Actualizando el objeto global
    objects.update(camaras)
    objects['last-image'] = None

    # No existe el metodo motor_debug
    # motor_execution.debug = opt.motor_debug

    motor_execution.restart()
    gevent.spawn(motor_execution.uart_readout_loop)

    # Iniciando el SweepControllet
    controlador = SweepController(camaras,
                                  motor_execution,
                                  sweep_status_broadcast,
                                  debug=True)
    objects['sweep-controller'] = controlador

    # configurando el broadcast de la camara
    came_0_config_broadcast = functools.partial(websockets_broadcast,
                                                identity=came_0.name,
                                                Kind='cfg')
    # devolviendo el estado del broadcast
    came_0_status_broadcast = functools.partial(camera_status_callback,
                                                identity=came_0.name)
    # Inicializando la camara
    came_0.start(came_0_config_broadcast, came_0_status_broadcast)

    resources = OrderedDict()
    # Agregando 2 pares al objeto OrderedDict
    # Equivale a .append
    resources['^/websocket'] = WSApplication
    resources['^/.*'] = app

    # Server de websocket
    server = WebSocketServer(('0.0.0.0', opt.port), Resource(resources))

    # Funcion que apaga el motor
    def shutdown():
        for motor in motor_api.motor_address.keys():
            motor_execution.set_hold_force(motor, False)
            gevent.sleep(0.01)

    motor_execution.set_axes_enabled(False)
    server.stop()
    zmq_ctx.destroy()
    sys.exit()

    gevent.signal(signal.SIGINT, shutdown)
    gevent.signal(signal.SIGTERM, shutdown)
    # Procesando una o varias solicitudes
    server.serve_forever()
示例#28
0
def runserver():
    server = WebSocketServer(('0.0.0.0', 5000),
                             Resource([('^/chat', ChatApplication),
                                       ('^/.*', DebuggedApplication(app))]),
                             debug=True)
    server.serve_forever()
示例#29
0
class MyWebSocketServer(Greenlet):
    """
    websocket服务器/当factory用吧
    """
    def __init__(self, port, urls, app, debug=False, **ssl_options):
        """端口监听器\n
        @param port: int 监听的端口\n
        @param urls: 链接的正则表达式列表\n
        @param apps: gevent-websocket封装的applications
        @param ssl_options: ssl参数
        """
        Greenlet.__init__(self)
        self.port = port
        self.urls = urls
        self.apps = app
        self.factory = None
        #sessionno生成器
        self.countGenerator = itertools.count(1, 1)
        self.allClients = {}
        #服务通道
        self.service = None
        #ssl_options
        root_ca = os.path.join(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "ca")
        if ssl_options:
            self.ssl_options = ssl_options
            self.ssl_options.update({
                "keyfile":
                os.path.join(root_ca, self.ssl_options['keyfile']),
                "certfile":
                os.path.join(root_ca, self.ssl_options['certfile'])
            })
        else:
            self.ssl_options = {}
        log.msg(self.ssl_options)
        self.debug = debug

    def addServiceChan(self, service):
        """
        添加服务通道
        :return:
        """
        self.service = service

    def getHost(self):
        """获取主机地址\n
        """
        return "0.0.0.0", self.port

    def getClientBySessionno(self, sessionno):
        """
        根据sessionno获取client
        :param sessionno:
        :return:
        """
        return self.allClients.get(sessionno, None)

    def _run(self):
        """启动监听器\n
        """
        log.msg('WebSocketServer on %s' % self.port)
        self.factory = WebSocketServer(self.getHost(),
                                       Resource([(i, self.apps)
                                                 for i in self.urls]),
                                       debug=self.debug,
                                       **self.ssl_options)
        self.factory.serve_forever()
示例#30
0
class Barnsworth(object):
    def __init__(self, **kwargs):
        self.irc_nick = kwargs.pop('irc_nick', DEFAULT_IRC_NICK)
        self.irc_host = kwargs.pop('irc_host', DEFAULT_IRC_HOST)
        self.irc_port = kwargs.pop('irc_port', DEFAULT_IRC_PORT)
        self.irc_channels = [x.strip('#') for x in
                             kwargs.pop('irc_channels', DEFAULT_IRC_CHANNELS)]
        # TODO: validate channel formatting?
        self.irc_client = IRCClient(self.irc_host,
                                    self.irc_nick,
                                    self.irc_port,
                                    reconnect=True)
        self.irc_client.add_handler(ping_handler, 'PING')
        self.irc_client.add_handler(self.on_irc_connect, _JOIN_CODE)
        self.irc_client.add_handler(self._on_irc)
        self.irc_client.add_handler(self.on_message, 'PRIVMSG')

        self.ws_port = kwargs.pop('ws_port', DEFAULT_WS_PORT)
        self.ws_server = WebSocketServer(('', self.ws_port),
                                         Resource({'/': WebSocketApplication}))
        defer_start = kwargs.pop('defer_start', False)
        if not defer_start:
            self.start()

    def start(self):
        self._start_irc()
        self._start_ws()

    def _on_irc(self, client, msg):
        if DEBUG:
            msg_content = ' '.join(msg.params[1:]).decode('utf-8')
            clean_msg = parsers.clean_irc_markup(msg_content)
            BLOG.debug('irc message').success(clean_msg)

    def on_irc_connect(self, client, msg):
        # TODO: need another handler to register a join failure?
        for channel in self.irc_channels:
            with BLOG.critical('joining channel %s' % channel):
                client.send_message(Join(channel))

    def on_message(self, client, msg):
        msg_content = ' '.join(msg.params[1:]).decode('utf-8')
        msg_content.replace(u'\x02', '')  # hmm, TODO
        try:
            action_dict = parsers.parse_irc_message(msg_content)
        except Exception as e:
            # log
            return
        action_ctx = ActionContext(action_dict)
        with BLOG.debug('activity publish'):
            self.publish_activity(action_ctx)
        return

    def publish_activity(self, action_ctx):
        action_json = json.dumps(action_ctx.action, sort_keys=True)
        for addr, ws_client in self.ws_server.clients.iteritems():
            ws_client.ws.send(action_json)

        # TODO: store action for activity batch service?
        with BLOG.debug('action context augmentation') as r:
            self._augment_action_ctx(action_ctx)
        with BLOG.debug('event detection') as r:
            event_list = self._detect_events(action_ctx)
            r.success('detected %s events' % len(event_list))
        for event in event_list:
            event_cn = event.__class__.__name__
            with BLOG.critical('publishing %r' % event_cn) as r:
                r.extras.update(event.to_dict())
                action_ctx.add_event(event)
                event_json = event.to_json()
                for addr, ws_client in self.ws_server.clients.iteritems():
                    ws_client.ws.send(event_json)
        return

    def _augment_action_ctx(self, action_ctx):
        action = action_ctx.action
        if action['is_anon']:
            # TODO: geo-augmentor
            return  # TODO?
        username = action['user']
        rc = ransom.Client()
        resp = rc.get(_USERDAILY_URL_TMPL % username)
        try:
            udc_dict = json.loads(resp.text)['userdailycontribs']
        except KeyError:
            return  # Log?
        user_daily = UserDailyInfo.from_dict(username, udc_dict)
        action_ctx.user_daily_info = user_daily
        return

    def _detect_events(self, action_ctx):
        try:
            event_types = EVENT_MAP[action_ctx.action_type]
        except KeyError:
            return []
        event_list = []
        for event_type in event_types:
            try:
                event = event_type.from_action_context(action_ctx)
                event_list.append(event)
            except events.Uneventful:
                # probably won't even log this
                # Uneventful is uneventful for a reason
                #print 'event not applicable: ', ue
                pass
            except Exception:
                BLOG.critical('event detection error').exception()
        return event_list

    def _start_irc(self):
        self.irc_client.start()

    def _start_ws(self):
        self.ws_server.serve_forever()
示例#31
0
def websockets_server():
    server = WebSocketServer((WS_LISTEN_HOST, WS_LISTEN_PORT), Resource({'/': WsServerApp}), debug=DEBUG)
    server.serve_forever()
示例#32
0
文件: __init__.py 项目: voidpp/pyccws
 def listen(self, port, host = ''):
     server = WebSocketServer((host, port), Resource({'/': self.client_handler}))
     logger.debug('server will listening on %d %s' % (port, server))
     server.serve_forever()
示例#33
0
def main():
    args = parse_args()
    async_mode = 'gevent'  # eventlet, gevent_uwsgi, gevent, threading

    logger.info('Running automate version {}', Env.version)
    from utils.io import delete_old_files
    delete_old_files(Env.tmp)

    # -------------------------------------------------------------------------

    if args.debug:
        async_mode = 'threading'
        Env.debug_mode = True
    else:
        from gevent import monkey
        monkey.patch_all()

    # -------------------------------------------------------------------------

    from flask_socketio import SocketIO
    import flask
    from www import app

    # -------------------------------------------------------------------------

    socketio = SocketIO(app,
                        json=flask.json,
                        async_mode=async_mode,
                        ping_interval=100 * 1000)
    register_routes(app, socketio)

    # -------------------------------------------------------------------------

    if args.backdoor:
        from www import backdoor
        backdoor.register_routes(app, socketio)

    # -------------------------------------------------------------------------

    logger.info('Listening on {host}:{port} (debug={debug})', **vars(args))
    Env.dump_info('Configuration in env.py')
    logger.info('removing old files from {}', Env.tmp)

    # -------------------------------------------------------------------------
    # from database.mongo import Mongo
    # ns = []
    # events = Mongo().events.find(({}))
    # for e in events:
    #     eid = str(e["_id"])
    #     if isinstance(e["to"], dict):
    #         did = e["document"]
    #         doc = Mongo().result_by_id(did)
    #         no_comment = doc.review is None
    #         user = e["to"]["id"]
    #         if no_comment:
    #             Mongo().update_event_fields(eid, to=user)
    #             ns.append(eid)
    # print(ns)
    # exit(0)

    # -------------------------------------------------------------------------

    if args.debug:
        app.run(debug=args.debug, host=args.host, port=args.port)
    else:
        from geventwebsocket import WebSocketServer
        http_server = WebSocketServer((args.host, args.port), app)
        http_server.serve_forever()

    return app, args
示例#34
0
    $ gunicorn -k "geventwebsocket.gunicorn.workers.GeventWebSocketWorker" \
        plot_graph:app
"""


import gevent
import random

from geventwebsocket import WebSocketServer, WebSocketApplication, Resource


class PlotApplication(WebSocketApplication):
    def on_open(self):
        for i in xrange(10000):
            self.ws.send("0 %s %s\n" % (i, random.random()))
            gevent.sleep(0.1)


def static_wsgi_app(environ, start_response):
    start_response("200 OK", [("Content-Type", "text/html")])
    return open("plot_graph.html").readlines()


if __name__ == "__main__":
    resource = Resource({
        '/': static_wsgi_app,
        '/data': PlotApplication
    })
    server = WebSocketServer(('', 8000), resource, debug=True)
    server.serve_forever()
示例#35
0
def start():
  logger.info("Starting pycaserver.")
  host = "192.168.1.5" #"127.0.0.1"
  port = 8888
  server = WebSocketServer((host, port), wsgi_app)
  server.serve_forever()