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()
class LogViewWorker(EntityWorker):
    def __init__(self, config_address, entity_port, http_port, ws_port):
        """
        :param config_address:  config进程的监听地址
        :param entity_port:     entity的服务接口
        :param http_port:       http的监听端口
        :param ws_port:         websocket的监听端口
        :return:
        """
        EntityWorker.__init__(self, "log_view", "log_view", entity_port, config_address)
        self._http_port = http_port
        self._ws_port = ws_port
        self._ws_server = None
        self._http_server = None

        global WS_PORT
        WS_PORT = ws_port

    def init_entity(self):
        self._ws_server = WebSocketServer(
            ('', self._ws_port),
            Resource(OrderedDict({"/": LogWebSocket}))
        )
        self._ws_server.start()

        self._http_server = HttpConnector(self._http_port)
        self._http_server.add_route("/showlog", ShowLog)
        self._http_server.add_route("/greplog", GrepLog)
        self._http_server.add_route("/nodes", AllNode)
        self._http_server.add_route("/nodemanage", NodeManage)
        self._http_server.add_route("/addnode", AddNode)
        self._http_server.add_route("/delnode", DelNode)
        self._http_server.start()

        WebSocketManager()
Beispiel #3
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)
Beispiel #4
0
 def __init__(self, game):
     WebSocketServer.__init__(self, ('', 8000), Resource({'/': PlayerSocket}))
     self.players = {}
     self.nextid = 0
     self.packer = msgpack.Packer()
     self.unpacker = msgpack.Unpacker()
     self.game = game
Beispiel #5
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
Beispiel #6
0
def server():
    s = WebSocketServer(
        ('0.0.0.0', 8001),
        Resource(OrderedDict([('/', WsApplication)]))
    )
    s.start()
    thread = Greenlet.spawn(s.serve_forever)
    yield s
    s.stop()
    thread.kill()
Beispiel #7
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()
Beispiel #8
0
    def serve_forever(self, server):
        self.wss = WebSocketServer(
            (self.address, self.port),
            ServerResource(self.apps, server),
            **self.kwargs
        )

        self.wss.serve_forever()
Beispiel #9
0
	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)
Beispiel #10
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()
    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 init_entity(self):
        self._ws_server = WebSocketServer(
            ('', self._ws_port),
            Resource(OrderedDict({"/": LogWebSocket}))
        )
        self._ws_server.start()

        self._http_server = HttpConnector(self._http_port)
        self._http_server.add_route("/showlog", ShowLog)
        self._http_server.add_route("/greplog", GrepLog)
        self._http_server.add_route("/nodes", AllNode)
        self._http_server.add_route("/nodemanage", NodeManage)
        self._http_server.add_route("/addnode", AddNode)
        self._http_server.add_route("/delnode", DelNode)
        self._http_server.start()

        WebSocketManager()
Beispiel #13
0
    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()
Beispiel #14
0
                'clients': [
                    getattr(client, 'nickname', 'anonymous')
                    for client in self.ws.handler.server.clients.values()
                ]
            }))

    def broadcast(self, message):
        for client in self.ws.handler.server.clients.values():
            client.ws.send(
                json.dumps({
                    'msg_type': 'message',
                    'nickname': message['nickname'],
                    'message': message['message']
                }))

    def on_close(self, reason):
        print "Connection closed! "


@flask_app.route('/')
def index():
    return render_template('index.html')


from geventwebsocket.handler import WebSocketHandler
WebSocketServer(('0.0.0.0', 5000),
                Resource({
                    '^/websocket': ChatApplication,
                    '^/.*': DebuggedApplication(flask_app)
                }),
                debug=False).serve_forever()
Beispiel #15
0
    while True:
        gevent.sleep(settings.websocket_timeout)
        for uid in wss:
            gevent.spawn(send_message, uid, 'ping')


def send_message(uid, message):
    try:
        wslist = wss[uid]
    except KeyError:
        return

    dead = []

    for i, ws in enumerate(wslist):
        try:
            ws.send(message)
        except WebSocketError:
            log.debug('WebSocket %s (uid=%s) id dead.' % (ws, uid))
            dead.append(i)

    wss[uid] = [i for j, i in enumerate(wss[uid]) if j not in dead]


gevent.spawn(ping_sockets)

log.info('ws server')
WebSocketServer((settings.websocket_host, settings.websocket_port),
                Resource({settings.websocket_url:
                          WsApplication})).serve_forever()
Beispiel #16
0
    def on_close(self, reason):
        current_client = self.ws.handler.active_client.custom_client
        token = current_client.get_token()
        print("on_close %s" % token)
        print(reason)
        self.broadcast_exclude_sender(
            json.dumps({
                "action": "left",
                "client_id": current_client.get_token()
            }), self.ws.handler.active_client)


#clients=ClientKeeper()

WebSocketServer(('', 5000),
                Resource({'/': ClientSocketApplication})).serve_forever()

# 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)

# WebSocketServer(
#     ('', 5000),
Beispiel #17
0
                        for k, v in node.items():
                            if k == "_":
                                continue
                            val = json.dumps(v)
                            app.backend.put(soul, k, v,
                                            diff[soul]['_']['>'][k])

                elif 'get' in payload:
                    get = payload['get']
                    soul = get['#']
                    ack = lex_from_graph(get, app.backend)
                    uid = trackid(str(uuid.uuid4()))
                    loggraph(graph)
                    resp = {'put': ack, '@': soul, '#': uid, 'ok': True}

                self.sendall(resp)
                self.sendall(msg)

        self.ws.send(message)

    def on_close(self, reason):
        print(reason)

    def sendall(self, resp):
        for client in self.ws.handler.server.clients.values():
            client.ws.send(json.dumps(resp))


geventserverapp = WebSocketServer(
    ('', 8000), Resource(OrderedDict([('/', GeventGunServer)])))
Beispiel #18
0

all_urls = [
    url('', Home),
    url('static/{path:any}', file_handler(root='static/'), name='static')
]

options = {}

# Template Engine
searchpath = ['']
engine = Engine(loader=FileLoader(searchpath), extensions=[
    CoreExtension(),
])
engine.global_vars.update({'h': html_escape})

options.update({'render_template': WheezyTemplate(engine)})

main = WSGIApplication(middleware=[
    bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory
],
                       options=options)

if __name__ == '__main__':
    WebSocketServer(('0.0.0.0', 8000),
                    Resource({
                        '^/chat': ChatApplication,
                        '^/.*': main
                    }),
                    debug=False).serve_forever()
Beispiel #19
0
        super(Messaging, self).__init__(*args, **kwargs)

    def on_connect(self, sid, environ):
        Messaging.logger.info("Socket connected %s", sid)
        pass

    def on_disconnect(self, sid):
        Messaging.logger.info("Socket disconnected %s", sid)

    def on_message(self, sid, data):
        Messaging.logger.info("Message received %s", str(data))

    def on_save(self, sid, data):
        with open("NONUWSGI_SAVED_DATA.txt", "w+") as f:
            f.write(str(data))
        Messaging.logger.info("Saving data: %s", str(data))
        self.emit("save", {"saved": True}, room=sid)

# async_handlers so that socketio sends emits as soon as that line is processed, not to wait for whole method to finish
sio = socketio.Server(logger=logging.getLogger(), engineio_logger=logging.getLogger(),
                      ping_timeout=120, ping_interval=10, async_handlers=True)
handler = Messaging('/socket2')
handler.server = sio
sio.register_namespace(handler)

# wrap WSGI application with socketio's middleware
application = socketio.Middleware(sio, application)

from geventwebsocket import WebSocketServer
WebSocketServer(('', 8001), application).serve_forever()
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)
Beispiel #21
0
 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()
Beispiel #22
0
def websockets_server():
    server = WebSocketServer((WS_LISTEN_HOST, WS_LISTEN_PORT), Resource({'/': WsServerApp}), debug=DEBUG)
    server.serve_forever()
Beispiel #23
0
import json
from datetime import datetime
from geventwebsocket import WebSocketServer, WebSocketApplication, Resource


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


# Try sending a JSON encoded message with timestamp

    def on_message(self, message):
        d = datetime.now()
        ds = d.strftime("%d/%m/%Y %H:%M:%S")
        data = json.dumps({'time': ds, 'text': 'Hello there!'})
        self.ws.send(data)

    def on_close(self, reason):
        print(reason)

WebSocketServer(('', 8000), Resource({'/': EchoApplication})).serve_forever()
Beispiel #24
0
def start():
	logger.info("Starting klystronserver.")
	host = "127.0.0.1"
	port = 8889
	server = WebSocketServer((host, port), wsgi_klystron_app)
	server.serve_forever()
Beispiel #25
0
        # Action.objects.create(
        #     author=Author.objects.get_or_create(name=action['author'])[0],
        #     content=action['message'],
        #     stream_id=action['stream']
        # )

        # self.push_socket.send_json({'message': message})

    def get_all(self, body):
        stream_id = int(body)
        actions = Action.objects.filter(stream_id=stream_id).values(
            'author__name', 'self_sha', 'timestamp', 'message')
        self.ws.send('actions:%s' % json.dumps(actions, cls=JSONEncoder))

    def new_action(self, body):
        print repr(body)
        action = json.loads(body)
        if set(action.keys()) != {'author', 'message', 'stream'}:
            self.ws.send('error: action has wrong keys: %r' % action.keys())
            return
        Action.objects.create(
            author=Author.objects.get_or_create(name=action['author'])[0],
            message=action['message'],
            stream_id=action['stream'])


resources = Resource({'/': ZmqApplication})

if __name__ == '__main__':
    WebSocketServer(('', 8001), resources).serve_forever()
Beispiel #26
0
def start(ctx, presentation, port, config, media, theme, style, debug):
    """Start revelation presentation command"""
    # Check if reveal.js is installed
    if not os.path.exists(REVEALJS_FOLDER):
        click.echo("Reveal.js not found, running installation...")
        ctx.invoke(installreveal)

    # Check for presentation file
    if os.path.isfile(presentation):
        path = os.path.dirname(presentation)
    else:
        click.echo("Error: Presentation file not found.")
        ctx.exit(1)

    # Check for style override file
    if style and (not os.path.isfile(style) or not style.endswith(".css")):
        click.echo("Error: Style is not a css file or does not exists.")
        ctx.exit(1)

    # Check for media root
    if not media:
        media = os.path.join(path, "media")

    if not os.path.isdir(media):
        # Running without media folder
        media = None

        click.echo("Media folder not detected, running without media")

    # Check for theme root
    if not theme:
        theme = os.path.join(path, "theme")

    if not os.path.isdir(theme):
        # Running without theme folder
        theme = None

    # Check for configuration file
    if not config:
        config = os.path.join(path, "config.py")

    if not os.path.isfile(config):
        # Running without configuration file
        config = None

        click.echo("Configuration file not detected, running with defaults.")

    click.echo("Starting revelation server...")

    # instantiating revelation app
    app = Revelation(presentation, config, media, theme, style, True)

    if debug:
        app = DebuggedApplication(app)

    PresentationReloader.tracking_path = os.path.abspath(path)

    click.echo("Running at http://localhost:{}".format(port))

    WebSocketServer(
        ("localhost", port),
        Resource([
            ("^/reloader.*", PresentationReloader),
            ("^/.*", DebuggedApplication(app)),
        ]),
    ).serve_forever()
Beispiel #27
0
'''
DATE: 2020/09/08
AUTHOR: Yanxi Li

ref:
https://gitlab.com/noppo/gevent-websocket

pip install gevent-websocket

gunicorn -k "geventwebsocket.gunicorn.workers.GeventWebSocketWorker" wsgi:websocket_app
'''

from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
from collections import OrderedDict


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)


WebSocketServer(
    ('', 8000),
    Resource(OrderedDict([('/', EchoApplication)]))).serve_forever()
Beispiel #28
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()
Run it using Gevent directly using:
    $ python plot_grapg.py

Or with an Gunicorn wrapper:
    $ 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()
# -*- 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()
Beispiel #31
0
from geventwebsocket import WebSocketServer, Resource
#from servers.ai import AIServer
#from servers.tick import TickServer
from servers.application import BrowserQuestApplication

if __name__ == "__main__":
    #AIServer().start()
    #TickServer().start()
    WebSocketServer(('', 8000),
                    Resource({'/': BrowserQuestApplication})).serve_forever()
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)
Beispiel #33
0
"""
When module ttg is executed start a wsgi web server
"""

import os

from geventwebsocket import WebSocketServer

from ttg.webapp import app

server = WebSocketServer(('0.0.0.0', int(os.environ['PORT'])), app)
server.serve_forever()
def app_worker(app, port):
    server = WebSocketServer(('', port), app)
    server.serve_forever()
Beispiel #35
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()
Beispiel #36
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()
Beispiel #37
0
            try:
                msg = os.tp_read(self.tuntap.fd, 1500)
                if not msg:
                    break
            except IOError:
                break
            if self.ws.closed:
                break
            self.ws.send(msg, True)

    def on_open(self):
        self.reader = gevent.spawn(self.read_fd)

    def on_close(self, reason):
        if (hasattr(self, 'reader')):
            self.reader.kill()

    def on_message(self, msg):
        if not msg:
            return
        os.tp_write(self.tuntap.fd, msg)

if __name__ == "__main__":
    server.tuntap = tuntap.tuntap(args.tuntap)
    wss = WebSocketServer((args.src, args.port), Resource({args.loc: server}))

    try:
        wss.serve_forever()
    except KeyboardInterrupt:
        wss.close()
    $ 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()
Beispiel #39
0
class APIServer():

    _api_prefix = '/api/1'

    def __init__(
            self,
            rest_api: RestAPI,
            ws_notifier: RotkiNotifier,
            cors_domain_list: List[str] = None,
    ) -> None:
        flask_app = Flask(__name__)
        if cors_domain_list:
            CORS(flask_app, origins=cors_domain_list)
        blueprint = create_blueprint(self._api_prefix)
        setup_urls(
            blueprint=blueprint,
            rest_api=rest_api,
            urls=URLS_V1,
        )

        self.rest_api = rest_api
        self.rotki_notifier = ws_notifier
        self.flask_app = flask_app
        self.blueprint = blueprint

        self.wsgiserver: Optional[WSGIServer] = None
        self.flask_app.register_blueprint(self.blueprint)
        self.ws_server: Optional[WebSocketServer] = None

        self.flask_app.errorhandler(HTTPStatus.NOT_FOUND)(endpoint_not_found)
        self.flask_app.register_error_handler(Exception, self.unhandled_exception)

    @staticmethod
    def unhandled_exception(exception: Exception) -> Response:
        """ Flask.errorhandler when an exception wasn't correctly handled """
        log.critical(
            'Unhandled exception when processing endpoint request',
            exc_info=True,
            exception=str(exception),
        )
        return api_response(wrap_in_fail_result(str(exception)), HTTPStatus.INTERNAL_SERVER_ERROR)

    def run(self, host: str = '127.0.0.1', port: int = 5042, **kwargs: Any) -> None:
        """This is only used for the data faker and not used in production"""
        self.flask_app.run(host=host, port=port, **kwargs)

    def start(
            self,
            host: str = '127.0.0.1',
            rest_port: int = 5042,
            websockets_port: int = 5043,
    ) -> None:
        """This is used to start the API server in production"""
        wsgi_logger = logging.getLogger(__name__ + '.pywsgi')
        self.wsgiserver = WSGIServer(
            listener=(host, rest_port),
            application=self.flask_app,
            log=wsgi_logger,
            error_log=wsgi_logger,
        )
        msg = f'rotki REST API server is running at: {host}:{rest_port}'
        print(msg)
        log.info(msg)
        self.wsgiserver.start()
        self.ws_server = WebSocketServer(
            listener=(host, websockets_port),
            application=WebsocketResource([
                ('^/', RotkiWSApp),
            ]),
            debug=False,
            environ={'rotki_notifier': self.rotki_notifier},
        )
        msg = f'rotki Websockets API server is running at: {host}:{websockets_port}'
        print(msg)
        log.info(msg)
        self.ws_server.start()

    def stop(self, timeout: int = 5) -> None:
        """Stops the API server. If handlers are running after timeout they are killed"""
        if self.wsgiserver is not None:
            self.wsgiserver.stop(timeout)
            self.wsgiserver = None
        if self.ws_server is not None:
            self.ws_server.stop(timeout)
            self.wsgiserver = None

        self.rest_api.stop()