Ejemplo n.º 1
0
def run():
    # Setup logging
    logger = logging.getLogger("")
    logger.handlers = []

    logger.setLevel(logging.INFO)
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_formatter = logging.Formatter('%(asctime)s %(module)-10s:%(lineno)-3s %(levelname)-7s %(message)s',"%y%m%d-%H:%M:%S")
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)
    logging.info("Logger configured")

    handler = ConnectionHandler()
    if SECURE:
        sc = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        sc.load_cert_chain('selfsigned.cert', 'selfsigned.key')

    server = websockets.serve(handler.connection, 'localhost', 8090)
    logging.basicConfig(level=logging.DEBUG)
    loop = asyncio.get_event_loop()
    loop.set_debug(enabled=True)

    # Python bug 23057 workaround for windows
    #asyncio.async(windows_dumb_do_nothing_routine())

    loop.run_until_complete(server)
    if SECURE:
        secure_server = websockets.serve(handler.connection, 'localhost', 8091, ssl=sc)
        loop.run_until_complete(secure_server)

    loop.call_later(1, display_startup_info)
    loop.run_forever()
Ejemplo n.º 2
0
    def __init__(self):
        """ Initialize system state and components """
        try:
            # Load state
            self.startup() # TODO make an init without cloned state an option
            # Create main event loop
            self.loop = asyncio.get_event_loop()
            # Create BPCon instance
            self.bpcon = BPConProtocol(self.conf, self.state)
            self.state.groups['G1'] = self.bpcon.peers # connect BPCon to Congregate instance
            self.paxos_server = websockets.serve(self.bpcon.main_loop, self.conf['ip_addr'], self.conf['port'], ssl=self.conf['ssl'])
            self.loop.run_until_complete(self.paxos_server)
            log.info("Started BPCon on port {}".format(self.conf['port']))

            # Create Congregate instance
            self.c = CongregateProtocol(self.loop, self.conf, self.bpcon)       
            self.congregate_server = websockets.serve(self.c.main_loop, self.conf['ip_addr'], self.conf['port']+1, ssl=self.conf['ssl'])
            self.loop.run_until_complete(self.congregate_server)
            log.info("Started Congregate on port {}".format(self.conf['port']+1))

            # Create API server
            self.web_server = websockets.serve(self.mainloop, self.conf['ip_addr'], self.conf['port']+2) 
            self.loop.run_until_complete(self.web_server)
            log.info("Started Web Server on port {}".format(self.conf['port']+2))

            # Add self to local group
            log.debug("adding self to local group")
            self.join_request()
            

            # Testing 
            if self.conf['is_client']:
                #self.c.reconfig()
                log.debug("is client. making test requests")
                for x in range(1):
                    request = "P,{},hello{}".format(x,x)
                    self.local_request("P,test,value")
                    self.local_request("P,test1,value1")
                    self.local_request("P,test2,value2")
                    self.local_request("P,test,value3")
                    self.local_request("D,test2,")
                    self.local_request(request)

                log.debug("requests complete")     
            else:
                #self.c.request_split()
                self.local_request("S,,")

                #self.c.request_merge("G2")
                self.group_request("M", "G2")

        except Exception as e:
            log.info(e)
Ejemplo n.º 3
0
    def start(self):
        self._debug("Starting server")
        # scopeless version of self
        this = self
        # A handler function that represents the event loop
        @asyncio.coroutine
        def handler(websocket, path):
            self._debug("Got client: " + str(websocket.remote_address))
            while True:
                # on each new loop
                tasks = []
                for task in this.handler_threads:
                    tasks.append(asyncio.async(
                        task(websocket)
                    ))
                # Blocking method that takes a list of thread ids
                # and yields a tuple when any one is finished. The first item
                # is a list of done thread ids, and the other is a list of
                # thread ids that have not finished yet
                done, pending = yield from asyncio.wait(
                    tasks,
                    return_when=asyncio.FIRST_COMPLETED
                )
        # start the websocket server
        ws_server = websockets.serve(handler, self.host, self.port)

        asyncio.get_event_loop().run_until_complete(ws_server)
        asyncio.get_event_loop().run_forever()
Ejemplo n.º 4
0
def run_pubsub_server(host, port):
    logger.info("Starting pubsub server on %s:%d", host, port)

    start_server = websockets.serve(client_handler, host, port, klass=get_protocol_handler_klass())

    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
Ejemplo n.º 5
0
def main():
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('remote_server', type=str, help='The server to connect to')
    parser.add_argument('remote_port', type=int, help='The port', default=8888)
    parser.add_argument('--host', type=str, help='Listen IP', default='')
    parser.add_argument('--port', type=int, help='The port', default=8765)
    parser.add_argument('--log', type=str, help='log level', default='INFO')
    args = parser.parse_args()
    numeric_level = getattr(logging, args.log.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % args.log)
    logging.basicConfig(level=numeric_level)

    loop = asyncio.get_event_loop()
    ws_server = loop.run_until_complete(websockets.serve(handle_ws, args.host, args.port, loop=loop))
    asyncio.ensure_future(read_from_server(args.remote_server, args.remote_port, loop))
    loop.call_later(60, gather_stats, loop)

    for sock in ws_server.server.sockets:
        addr = sock.getsockname()
        logging.info('Listening for Websocket connections on %s:%s', addr[0], addr[1])

    loop.run_forever()
    loop.close()

    return 0
Ejemplo n.º 6
0
    def _start_thread(self):
        self.server_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.server_loop)

        async def time(websocket, path):
            id = self.websocket_id
            self.websocket_id += 1
            self.websocket_messages[websocket] = []
            self.messages_available[websocket] = asyncio.Event()

            print("Websocket {0} connected - {0} total.".format(id, len(self.websocket_messages)))
            try:
                while True:
                    await self.messages_available[websocket].wait()
                    self.messages = self.websocket_messages[websocket]
                    for message in self.messages:
                        msg = "{0},{1},{2},{3}".format(message[0], message[1], message[2], message[3])
                        await websocket.send(msg)
                    self.messages_available[websocket].clear()
                    self.websocket_messages[websocket] = []
            finally:
                print("Websocket {0} disconnected".format(id))
                del self.websocket_messages[websocket]

        start_server = websockets.serve(time, '0.0.0.0', 5678)

        asyncio.get_event_loop().run_until_complete(start_server)
        asyncio.get_event_loop().run_forever()
Ejemplo n.º 7
0
def main():
    parser = argparse.ArgumentParser(description='A simple DNS tunnel over websocket')
    parser.add_argument('-b', action='store', dest='bind_address', default='127.0.0.1',
                        help='bind to this address, default to 127.0.0.1')
    parser.add_argument('-p', action='store', dest='bind_port', type=int, default=5353,
                        help='bind to this port, default to 5353')
    parser.add_argument('--debug', action='store_true', dest='debug', default=False,
                        help='enable debug outputing')
    args = parser.parse_args(sys.argv[1:])
    if 'PORT' in os.environ:
        # we are probably in heroku environment
        port = int(os.environ['PORT'])
        addr = '0.0.0.0'
    else:
        port = args.bind_port
        addr = args.bind_address
    if args.debug:
        logging_level = logging.DEBUG
    else:
        logging_level = logging.INFO
    logging.basicConfig(level=logging_level,
                        format='%(asctime)s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    start_server = websockets.serve(handle, addr, port)
    asyncio.get_event_loop().run_until_complete(start_server)
    logging.info('listening on %s:%d' % (addr, port))
    asyncio.get_event_loop().run_forever()
Ejemplo n.º 8
0
def run_server(host, port):
    logger.info("Starting control server on %s:%d", host, port)

    start_server = websockets.serve(client_handler, host, port)

    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
Ejemplo n.º 9
0
def run_server():
    loop = asyncio.get_event_loop()
    server = SimServer(loop=loop)
    start_server = websockets.serve(server, 'localhost', 3000)

    try:
        webbrowser.open(
            "file://{}".format(
                abspath(pjoin(dirname(abspath(__file__)), '..', 'WebDrone', 'index.html'))
            )
        )
        s = loop.run_until_complete(start_server)
        logger.info(
            'simulation is serving on {}'.format(s.sockets[0].getsockname())
        )
        loop.run_forever()
    except KeyboardInterrupt:
        logger.debug('capture ctrl-C in sim main.')
        coros = [
            server.close()
        ]
        loop.run_until_complete(cleanup(coros))
    finally:
        loop.close()
        logger.info("exit.")
Ejemplo n.º 10
0
def servewebsocketrunforever(portnumber):
    print("serving", ipaddress, portnumber)
    start_server = websockets.serve(handler, ipaddress, portnumber)
    mainasyncloop.run_until_complete(start_server)
    receivertask = asyncio.async(receiverall())
    producertask = asyncio.async(producer())
    mainasyncloop.run_forever()
Ejemplo n.º 11
0
 def __init__(self, host, port):
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
     self.server = websockets.serve(self.receiver, host, port, loop=self.loop)
     self.host = host
     self.port = port
     WebSocket.loop = self.loop
Ejemplo n.º 12
0
 def run(self):
     logger.info('Connecting to webserver %s...', self.server_url)
     self.websocket = yield from websockets.connect(self.server_url)
     logger.info('Listening connections...')
     yield from websockets.serve(self.on_client, '0.0.0.0', 8081)
     yield from self.loop()
     logger.info('Proxy stop')
Ejemplo n.º 13
0
def startup(callback):
    controlws = ControlWS()
    controlws.callback = callback
    start_server = websockets.serve(controlws.handler, 'tribot.shack', 1337)

    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
Ejemplo n.º 14
0
def main():
	print("Serving WebSockets on "+config['host']+" port "+config["port"]+" ...")
	temppath = os.path.join(os.path.sep, "tmp")
	start_server = websockets.serve(hello, config['host'], config['port'])

	asyncio.get_event_loop().run_until_complete(start_server)
	asyncio.get_event_loop().run_forever()
Ejemplo n.º 15
0
def lance_broadcast():
    start_server = websockets.serve(handler_cast, get_lan_ip(), 8003)
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    asyncio.get_event_loop().run_until_complete(start_server)
    print("Websocket connection launched on port 8003")
    asyncio.get_event_loop().run_forever()
Ejemplo n.º 16
0
def main():
    loop = asyncio.get_event_loop()

    # обычно websocket работают через HTTP(S) порт (80/443); чтобы иметь
    # возможность запускать от non-root пользователя, используем 8765
    start_server = websockets.serve(
        hello,
        WEBSOCKET_SERVER['address'],
        WEBSOCKET_SERVER['port']
    )
    try:
        print(str.format(
            'Try to run websocket server: [{}:{}]',
            WEBSOCKET_SERVER['address'], WEBSOCKET_SERVER['port']
        ))

        loop.run_until_complete(start_server)
    except OSError as e:
        print(str.format('[%] <e>', e))
        sys.exit(1)
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.close()
        print('[*] Websocket server shut down!')
Ejemplo n.º 17
0
async def start_websockets(websocket_handlers):
    import websockets
    futures = []
    for handler, host, port in websocket_handlers:
        ws_future = websockets.serve(handler, host, port)
        futures.append(ws_future)
    await asyncio.gather(*futures)
Ejemplo n.º 18
0
def main():
	"""
	Setup and run all subroutines.
	"""
	global socks, queue, authed, sessions, queuehash, upkeepThread, pluginUpkeeps

	pluginList = plugins.getPlugins()
	pluginUpkeeps = list(filter(lambda module: hasattr(module, "upkeep"), pluginList))
	comm.buildCommands(pluginList)
	laserqueue.buildLists(pluginList)

	# Load the queue if -b is used
	if args.backup:
		if os.path.exists("cache.json"):
			queue = laserqueue.Queue.load(open("cache.json"))
		else:
			json.dump({}, open("cache.json", "w"))

	color_print("Serving WebSockets on 0.0.0.0 port {port} ...", port=config["port"])

	# Create the upkeep thread
	upkeepThread = threading.Thread(target=upkeep)
	upkeepThread.daemon = True
	upkeepThread.start()

	# Create the server event loop
	start_server = websockets.serve(server, "0.0.0.0", config['port'])
	loop = asyncio.get_event_loop()
	try:
		loop.run_until_complete(start_server)
		loop.run_forever()
	except KeyboardInterrupt:
		quit(0)
Ejemplo n.º 19
0
 def __init__(self):
     self.running = False
     self.conn_queues = []
     self.worker_method = self._run
     self.pipe = Pipe()
     super(WebsocketsServer, self).__init__(self)
     self.server = websockets.serve(self.new_conn, 'localhost', 8765)
Ejemplo n.º 20
0
def testWebsocketTransport():
	@asyncio.coroutine
	def serverRoutine(websocket, path):
		print("new connection")
		receiver = TransportGateway(enc, WebsocketTransport(websocket), debugMode = True)
		receiver.exposeObjectImplementation(TestImplementation)
		yield from asyncio.sleep(0.5)
		a = yield from  (receiver << Test.requestNew(1))
		print(a)
		b = yield from a.echo("asd")
		print(b)
		b = yield from a.echo("asd")
		print(b)
		b = yield from a.echo("asd")
		print(b)

		#yield from receiver.serverMode()
		print("connection closed")


	@asyncio.coroutine
	def clientRoutine():
		websocket = yield from websockets.connect('ws://localhost:8765/')
		return TransportGateway(enc, WebsocketTransport(websocket), debugMode = True)
		

	start_server = websockets.serve(serverRoutine, 'localhost', 8765)
	asyncio.get_event_loop().run_until_complete(start_server)
	asyncio.get_event_loop().run_forever()
Ejemplo n.º 21
0
 def make_server(self, port, listen='0.0.0.0'):
     context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
     context.load_cert_chain('/etc/ssl/certs/ssl-cert-snakeoil.pem',
                             '/etc/ssl/private/ssl-cert-snakeoil.key')
     self.log.info('UVC management server started on port %i' % port)
     return websockets.serve(self.handle_camera,
                             listen, port, ssl=context)
Ejemplo n.º 22
0
  def listen(self, port, host):
    logger.info("Server listening on %s:%s.", host, port)
    self.store.lock()

    green.await_coro(
        websockets.serve(green.coroutine(self.accept),
                         host, port))
Ejemplo n.º 23
0
def main():
    loop = asyncio.get_event_loop()
    coro = serial.aio.create_serial_connection(loop, serPort, url='/dev/arduino', baudrate=38400)
    ser_task = asyncio.ensure_future(coro)
    loop.run_until_complete(coro)
    ###print("ser_task result: {}".format(ser_task.result()))
    ser_transport = ser_task.result()[0]
    ser_protocol = ser_task.result()[1]
    ###writer = asyncio.StreamWriter(ser_transport, ser_protocol, reader, loop)
    ###print(ser_transport)

    #loop = asyncio.get_event_loop()
    #coro  = serial.aio.create_serial_connection(loop, serPort, '/dev/arduino',baudrate=38400)
    #ser_task = asyncio.ensure_future(coro)
    #loop.run_until_complete(coro)
    #print("ser_task result 0: {}".format(ser_task.result()[0]))
    #print("ser_task result 1: {}".format(ser_task.result()[1].data_received))
    #newtask = loop.create_task(ser_task.result()[1].data_received)
    #print(newtask)
    #print("is coroutine function? {!s}".format(asyncio.iscoroutinefunction(ser_task.result()[1].data_received))
    #print("is coroutine? {}".format( asyncio.iscoroutine(ser_task.result()[1].data_received) )
    #print(asyncio.iscoroutinefunction(ser_task.result()[1].data_received))
    
    myhandler = functools.partial(handler,mytasks=[],mycallbacks=[ser_transport.write],ser=ser_protocol)
    #myhandler = functools.partial(handler,mytasks=[ser_task.result()[1].data_received])
    start_server = websockets.serve(myhandler, 'localhost', 8765)
    ws_task = asyncio.ensure_future(start_server)
    asyncio.get_event_loop().run_until_complete(start_server)
    print("ws_task results: {}".format(ws_task.result()))
    ws_serv = ws_task.result()

    #loop = asyncio.get_event_loop()
    #coro = serial.aio.create_serial_connection(loop, serPort, '/dev/arduino',baudrate=38400,timeout=0.2)
    #loop.run_until_complete(coro)
    asyncio.get_event_loop().run_forever()
Ejemplo n.º 24
0
 def run_server(self):
     """Create websocket server and run it until it gets Ctrl+C or SIGTERM.
     :param config: config dictionary
     """
     try:
         loop = asyncio.get_event_loop()
         server = loop.run_until_complete(websockets.serve(self._connection_handler, self.host, self.port))
         loop.add_signal_handler(signal.SIGTERM, loop.stop)
         logger.info("listening on %s:%s" % (self.host, self.port))
         consumer = None
         # create socket message consumer
         consumer = SocketMessageConsumer(self.broker_url, self.broadcast)
         consumer_thread = Thread(target=consumer.run)
         consumer_thread.start()
         loop.run_forever()
     except KeyboardInterrupt:
         pass
     finally:
         logger.info("closing server")
         server.close()
         loop.run_until_complete(server.wait_closed())
         loop.stop()
         loop.run_forever()
         loop.close()
         if consumer:
             consumer.close()
Ejemplo n.º 25
0
    def __run_loop(self):
        # Set event loop
        if self.background:
            logging.info("Running in background")
            asyncio.set_event_loop(self.loop)

        # Create the loop server
        self.server = self.loop.run_until_complete(websockets.serve(self.handler, self.address, self.port))

        try:
            logging.info("Starting server")
            self.loop.run_forever()

        except KeyboardInterrupt:
            logging.info("Keyboard Interrupt received.")

        finally:
            # Tell any clients that we're closing
            self.server.close()
            self.loop.run_until_complete(asyncio.sleep(0.1))

            # Gather any remaining tasks so we can cancel them
            asyncio.gather(*asyncio.Task.all_tasks()).cancel()
            self.loop.stop()

            logging.info("Cancelling pending tasks...")
            self.loop.run_forever()

            logging.info("Stopping Server...")
            self.loop.close()
Ejemplo n.º 26
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config', default=default.GEOFFREY_RC_FILE)
    parser.add_argument('path', nargs='+')
    args = parser.parse_args()
    config = Config(args.config, create=True)

    main = config['geoffrey']
    host = main.get('host', default.HOST)
    websocket_port = main.get('websocket_port', default.WEBSOCKET_PORT)
    webserver_port = main.get('webserver_port', default.WEBSERVER_PORT)

    loop = asyncio.get_event_loop()

    em = EventManager()
    plugins = get_plugins(config, output_queue)
    for subscriptions in plugins.call('get_subscriptions'):
        em.add_subscriptions(subscriptions)

    mask = em.get_mask()

    asyncio.Task(websockets.serve(websocket_server, host, websocket_port))
    asyncio.Task(watch_files(args.path, mask=mask))
    asyncio.Task(em.consume_events(event_queue, output_queue))
    webapp.run()
    loop.run_forever()
Ejemplo n.º 27
0
    def run(self):
        """
        Run the dumpling hub.

        Starts two websocket servers: one to receive dumplings from zero or
        more instances of ``nd-sniff``; and another to send those dumplings to
        zero or more dumpling eaters. Also creates its own dumplings at regular
        intervals to send system status information to all connected dumpling
        eaters.
        """
        dumpling_in_server = \
            websockets.serve(self._grab_dumplings, self.address, self.in_port)
        dumpling_out_server = \
            websockets.serve(self._emit_dumplings, self.address, self.out_port)

        loop = asyncio.get_event_loop()

        try:
            srv_in = loop.run_until_complete(dumpling_in_server)
            srv_out = loop.run_until_complete(dumpling_out_server)
        except OSError as e:
            raise NetDumplingsError(
                "Cannot instantiate dumpling hub: {0}".format(e))

        status_task = asyncio.ensure_future(self._announce_system_status())

        self._logger.info("Dumpling hub initiated; waiting for connections")

        in_uri = "ws://{0}:{1}".format(self.address, self.in_port)
        out_uri = "ws://{0}:{1}".format(self.address, self.out_port)
        self._logger.info(
            "Dumplings in: {0}  out: {1}".format(in_uri, out_uri)
        )

        try:
            loop.run_forever()
        except KeyboardInterrupt:
            self._logger.warning(
                "Caught keyboard interrupt; attempting graceful shutdown...")
        finally:
            srv_in.close()
            srv_out.close()
            loop.run_until_complete(srv_in.wait_closed())
            loop.run_until_complete(srv_out.wait_closed())
            if not status_task.cancelled():
                status_task.set_result(None)
            self._logger.info("Dumpling hub signing off.  Thanks!")
Ejemplo n.º 28
0
	def run(self):
		loop = asyncio.new_event_loop()
		asyncio.set_event_loop(loop)

		start_server = websockets.serve(self.hello, self.ip, self.port)

		asyncio.get_event_loop().run_until_complete(start_server)
		asyncio.get_event_loop().run_forever()
Ejemplo n.º 29
0
def main():
	temppath = os.path.expanduser(os.path.join("~", "AppData", "Local", "Temp"))
	open(os.path.join(temppath, "topage.json"), "w").close() # initialize file
	open(os.path.join(temppath, "toscript.json"), "w").close() # initialize file
	start_server = websockets.serve(hello, config["host"], config['port'])

	asyncio.get_event_loop().run_until_complete(start_server)
	asyncio.get_event_loop().run_forever()
Ejemplo n.º 30
0
 def run_server():
     async def empty_server(websocket, path):
         data = await websocket.recv()
         await asyncio.sleep(0.02)
         await websocket.send(data)
     server = websockets.serve(empty_server, '127.0.0.1', open_port, loop=event_loop)
     event_loop.run_until_complete(server)
     event_loop.run_forever()
Ejemplo n.º 31
0
import random
import websockets
import http

#  agent/status
#  build/status
#  release/status
#
BUILD_STATUS_PATH = "BUILD/STATUS"
RELEASE_STATUS_PATH = "RELEASE/STATUS"


async def time(websocket, path):
    print("current path", path)
    if path.upper() == BUILD_STATUS_PATH:
        while True:
            now = datetime.datetime.utcnow().isoformat() + "Z"
            await websocket.send(now)
            await asyncio.sleep(random.random() * 3)

    elif path.upper() == RELEASE_STATUS_PATH:
        while True:
            now = datetime.datetime.utcnow().isoformat() + "Z"
            await websocket.send(now)
            await asyncio.sleep(random.random() * 3)


start_server = websockets.serve(time, "127.0.0.1", 9001)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 32
0
import asyncio
import datetime
import websockets


# 接收客户端消息并处理,这里只是简单把客户端发来的返回回去
async def recv_msg(websocket):
    while True:
        now = datetime.datetime.utcnow().isoformat() + "Z"
        recv_text = await websocket.recv()
        print(f'获取到的消息:{recv_text}')
        response_text = f"你发送的消息为: {recv_text} {now}"
        await websocket.send(response_text)


# 服务器端主逻辑
# websocket和path是该函数被回调时自动传过来的,不需要自己传
async def main_logic(websocket, path):
    await recv_msg(websocket)


start_server = websockets.serve(main_logic, "127.0.0.1", 5678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 33
0
        # Catch the exception.
        except Exception as err:
            print(err)
            break

    # Remove the computer from the computer queue.
    if cur_computer is not None:
        cur_computer.computer_status = False
        if cur_computer in computer_queue:
            computer_queue.remove(cur_computer)
        print('Removed the computer from the computer queue.')

    print('Connection closed.')


# Load the SSL Context.
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain(certfile='./a.pem', keyfile='./a.key')

# Start the main service loop.
start_server = websockets.serve(main_service_loop,
                                '0.0.0.0',
                                82,
                                ssl=ssl_context,
                                read_limit=2**25,
                                max_size=2**25)
print('Start Service...')
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 34
0
import json

stringify = json.JSONEncoder().encode
parse = json.JSONDecoder().decode

clients = []
bws = BitmexWS()


def sendToAll(obj):
    str = stringify(obj)
    for ws in clients:
        asyncio.get_event_loop().create_task(ws.send(str))


async def hello(ws, path):
    clients.append(ws)
    while True:
        try:
            str = await ws.recv()
            bws.run(parse(str))
        except:
            clients.remove(ws)
            break


asyncio.get_event_loop().run_until_complete(
    websockets.serve(hello, 'localhost', 3000))

asyncio.get_event_loop().run_forever()
Ejemplo n.º 35
0
        import socketserver
        ## Via: https://stackoverflow.com/questions/4465959/python-errno-98-address-already-in-use/25529620#25529620
        socketserver.TCPServer.allow_reuse_address
        Handler = http.server.SimpleHTTPRequestHandler
        with socketserver.TCPServer(("localhost", port), Handler) as httpd:
            print("Serving HTTP on port", port)
            httpd.serve_forever()


## This is too annoying because of address re-use.
# serve_http( port_http )

import argparse

parser = argparse.ArgumentParser(
    description="A compute server for interactive layer editing.")
parser.add_argument("--port",
                    type=int,
                    default=port_websocket,
                    help="The port to listen on.")
args = parser.parse_args()
port_websocket = args.port

print("WebSocket server on port", port_websocket)
start_server = websockets.serve(layer_server,
                                'localhost',
                                port_websocket,
                                max_size=None)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 36
0
import asyncio
import websockets


async def hello(websocket, path):
    name = await websocket.recv()
    print(f"< {name}")

    greeting = f"Hello {name}!"

    await websocket.send(greeting)
    print(f"> {greeting}")


start_server = websockets.serve(hello, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 37
0

async def hello(websocket, path):
    while True:
        # logger.debug("websokcet服务端发送的数据:{}".format(sensor_dt))
        sensor_LS = [sensor for sensor in sensor_CD.values()]  # 数据格式转换 转换为
        # 修改数据格式
        video_LS = [video for video in video_CD.values()]
        # logger.info("监控列表")
        # logger.info(video_LS)
        # info = {"sensors": sensor_LS, "videos": video_LS}
        info = {"sensors": sensor_LS}
        # info = {"videos": video_LS}
        logger.info("发送的数据")
        logger.info(info)
        data_json = json.dumps(info, ensure_ascii=False)  # 修改为发送网关列表
        await websocket.send(data_json)

        logger.debug(">>>发送数据 {}".format(data_json))
        await asyncio.sleep(5)


if __name__ == "__main__":
    t1 = threading.Thread(target=sub)
    t1.start()
    # t2 = threading.Thread(target=sub_video())
    # t2.start()
    start_server = websockets.serve(hello, '0.0.0.0', 9999)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
Ejemplo n.º 38
0
            await asyncio.sleep(100)


async def send_temperature(data):
    print('in send : ', data)
    async with websockets.connect(
            'ws://192.168.1.28:5678/broadcast/temperature/read') as websocket:
        #     try:
        #        resp = await websocket.recv()
        await websocket.send(value)


async def trigger_method(message):
    print(message)
    y = json.loads(message)
    print(y["method"])
    if y["method"] == "takeBottle":
        import RPi.GPIO as GPIO
        import time
        #        ledPin = y.ledPin
        setup()
        loop()


#    if

#start_server = websockets.serve(pub_sub, '127.0.0.1', 5678)
start_server = websockets.serve(pub_sub, '192.168.1.28', 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 39
0
 def serve(self, host="0.0.0.0", port=5000):
     return websockets.serve(self.handle, host, port)
Ejemplo n.º 40
0
def runThread(id_u):
    l = asyncio.new_event_loop()
    asyncio.set_event_loop(l)
    l.run_until_complete(websockets.serve(sendCommand, 'localhost', 9000))
    l.run_forever()
Ejemplo n.º 41
0
#!/usr/bin/env python

# WS server example

import asyncio
import websockets
import json
from dialogflow_v1 import DialogflowApi
from flow_manager import flow_control


async def hello(websocket, path):
    clientJson = await websocket.recv()
    print(f"< {clientJson}")

    greeting = flow_control(clientJson)

    await websocket.send(greeting)
    print(f"> {greeting}")


start_server = websockets.serve(hello, 'localhost', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 42
0
async def counter(websocket, path):
    # register(websocket) sends user_event() to websocket
    await register(websocket)
    try:
        async for message in websocket:
            msg = json.loads(message)
            msg['src'] = websocket.uuid
            pp.pprint(msg)
            message = json.dumps(msg)

            if 'message_type' in msg and msg['message_type'] == 'SUBSCRIBE':
                if 'channel' in msg and msg['channel'] in channels:
                    channels[msg['channel']][websocket.uuid] = websocket
                continue

            if 'dst' in msg:
                await notify_dst(msg['dst'], message)
            else:
                await notify_all_users(message)
    except Exception as e:
        pp.pprint(e)
    finally:
        await unregister(websocket)

start_server = websockets.serve(counter, '127.0.0.1', 5678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Ejemplo n.º 43
0
    try:

        interface = Interface()

        async def api_call(websocket, path):
            async for message in websocket:
                try:
                    msg = json.loads(message.replace("\\", "/"))
                    retMsg = interface.parse_command(msg)
                    rxStr = json.dumps(retMsg)
                    await websocket.send(rxStr)
                except Exception as e:
                    await websocket.send(
                        json.dumps({
                            'status':
                            False,
                            'error':
                            'cannot parse JSON message: {}'.format(str(e))
                        }))

        asyncio.get_event_loop().run_until_complete(
            websockets.serve(api_call, DEFAULT_HOST_NAME, port))
        asyncio.get_event_loop().run_forever()

    except Exception:
        if isAlex:
            client.captureException()
        else:
            print('Exception caught in main.py')
Ejemplo n.º 44
0
        raise ValueError('user without cookie connected')

    connection = Connection(websocket, userId, sessionId, path)
    consumer_task = asyncio.ensure_future(consumer_handler(connection))
    done, pending = await asyncio.wait(
        [consumer_task],
        return_when=asyncio.FIRST_COMPLETED,
    )
    for task in pending:
        task.cancel()


if __name__ == '__main__':
    for dict_name in ['simple', 'medium', 'hard']:
        words = []
        with open('dicts/%s.txt' % dict_name) as infile:
            for line in infile:
                line = line.strip()
                if line != '':
                    words.append(line)
        DICTS[dict_name] = words

    start_server = websockets.serve(
        server,
        "localhost",
        8080  #, ssl=ssl_context
    )

    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
Ejemplo n.º 45
0
def get_request_id(client_request):
    client_request_json = json.loads(client_request)
    request_id = client_request_json.get("id")
    return request_id


async def start_bot(websocket, path):
    peer = Peer(PeerType.user, 201707397, "-2675024364153751067")
    server_text_message = ServerTextMessage("/start", peer)
    await websocket.send(server_text_message.get_json_str())
    name = await websocket.recv()
    request_id = get_request_id(name)
    read_update = ServerReadUpdate(request_id)
    await websocket.send(read_update.get_json_str())

    server_text_message = ServerPhotoMessage(peer)
    await websocket.send(server_text_message.get_json_str())
    client_request = await websocket.recv()
    request_id = get_request_id(client_request)
    read_update = ServerReadUpdate(request_id)
    await websocket.send(read_update.get_json_str())
    print("*********************SuccessFull*********************")
    await websocket.recv()


start_server = websockets.serve(start_bot, 'localhost', '8765')

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 46
0
    states1 = [tuple_namer('Sensor1', i) for i in state_combinations]
    initial_state1 = tuple_namer('Sensor1', (3, 'running', 'running'))
    actions_states1 = create_action_states(states1)
    agent1 = Agent(actions_states1, state_rewards, initial_state1, wakeup,
                   Sarsa, 1011, loop)
    """agent 2"""
    states2 = [tuple_namer('Sensor2', i) for i in state_combinations]
    initial_state2 = tuple_namer('Sensor2', (16, 'running', 'sleeping'))
    actions_states2 = create_action_states(states2)
    agent2 = Agent(actions_states2, state_rewards, initial_state2, wakeup,
                   Sarsa, 1022, loop)
    """message passing between agents"""
    qs = {'Sensor1': agent1.sensing_q, 'Sensor2': agent2.sensing_q}
    """message passing to websocket"""
    writerq = asyncio.PriorityQueue(maxsize=2048)
    start_server = websockets.serve(socketwriter, '127.0.0.1', 8080)
    """now define our environments"""
    env_reactions = {
        'go_to_sleep': reaction_default,
        'wakeup': reaction_default,
        'noop': reaction_default
    }
    env1 = Environment(env_reactions, [copy.deepcopy(battery_action)],
                       agent1.sensing_q, agent1.action_q)
    env2 = Environment(env_reactions, [copy.deepcopy(battery_action)],
                       agent2.sensing_q, agent2.action_q)
    """now run the simulation"""

    tasks = [
        agent1.experience_environment(),
        env1.react_to_action(),
Ejemplo n.º 47
0
    print("Connection au master....")
    master = dronekit.connect("/dev/ttyACM0", baud=56700)
    time.sleep(5)
    print("Master: " + str(master.version))
    return slave, master


async def processus(websocket, path):
    message = await websocket.recv()
    print(message)
    while True:
        latM, lonM, headM = master.location.global_frame.lat, master.location.global_frame.lon, master.heading
        latS, lonS, headS = slave.location.global_frame.lat, slave.location.global_frame.lon, slave.heading
        print("master " + headM)
        print("slave " + headS)
        await websocket.send('{"type":"masterP","lat":' + str(latM) +
                             ',"lon":' + str(lonM) + ',"head":' + str(headM) +
                             '}')
        await websocket.send('{"type":"slaveP","lat":' + str(latS) +
                             ',"lon":' + str(lonS) + ',"head":' + str(headS) +
                             '}')
        time.sleep(5)


slave, master = connect()
start_server = websockets.serve(processus, "192.168.43.62", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 48
0
async def main_logic(websocket, path):
    await check_permit(websocket)
    await recv_msg(websocket)


if __name__ == '__main__':
    global flask_app

    wifi_check()
    flask_app = app.webapp()
    flask_app.startthread()

    bs_threading = threading.Thread(target=batteryStatus)
    bs_threading.setDaemon(True)
    bs_threading.start()
    while 1:
        try:  #Start server,waiting for client
            start_server = websockets.serve(main_logic, '0.0.0.0', 8888)
            asyncio.get_event_loop().run_until_complete(start_server)
            print('waiting for connection...')
            # print('...connected from :', addr)
            break
        except Exception as e:
            print(e)

    try:
        asyncio.get_event_loop().run_forever()
    except Exception as e:
        print(e)
Ejemplo n.º 49
0
    UINPUT.syn()

    if USERS:  # asyncio.wait doesn't accept an empty list
        message = state_event()
        await asyncio.wait([user.send(message) for user in USERS])

async def counter(websocket, path):
    await websocket.send(welcome_event())

    USERS[websocket] = [False for x in KEYS]
    try:
        while True:
            await notify_state()

            message = await websocket.recv()
            data = json.loads(message)
            bool_data = [bool(x) for x in data]
            if len(bool_data) == len(KEYS):
                USERS[websocket] = bool_data
            else:
                logging.error("unsupported event: {}", message)
    finally:
        USERS.pop(websocket)
        await notify_state()


start_server = websockets.serve(counter, "0.0.0.0", 6789)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 50
0
            msg = await websocket.recv()
            print("msg")

            # if msg == "break":
            #     y+=1
            #     x=-1

            # if msg == "end":
            #     img.save(f'{random.randint(1,x)}.png')
            #     img.show()

            # if float(msg) > 0:
            #     msg = float(msg)
            #     c = math.floor((int(msg*1000) << 3)/1000)
            #     c=200-c
            #     x+=1
            #     img.putpixel((x,y), (c,c,c))
            #     print(x,y,f"Pixel Value : {c}")
            # else:
            #     x+=1
            #     img.putpixel((x,y), (0,0,0))
            #     #print(x,y)

        except Exception as e:
            pass  #print(e)


start_server = websockets.serve(main, "192", 10)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 51
0
import base64
import asyncio
import websockets
host = "localhost"
port = "3001"


# 클라이언트 접속이 되면 호출된다.
async def accept(websocket, path):
    with open("result.png", "rb") as f:
        img_string = base64.b64encode(f.read())  # .encode('utf8')
        print(img_string)
        await websocket.send(img_string)


# 웹 소켓 서버 생성.호스트는 localhost에 port + 1로 생성한다. (port는 서버 포트여서 다르게 줬다)
start_server = websockets.serve(accept, host, port)
# 비동기로 서버를 대기한다.
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

# def sending():
#     with open("../result.jpeg", "rb") as f:
#         img_string = base64.b64encode(f.read()).encode('utf8')
#
#
# sending()
Ejemplo n.º 52
0
def start_web(addr='localhost', port=8910):
    start_server = websockets.serve(serve, addr, port, create_protocol=FileServer)
    asyncio.get_event_loop().run_until_complete(start_server)
Ejemplo n.º 53
0
def create_word_sender_server(in_queue, host=HOST, port=PORT):
    word_sender = create_word_sender(in_queue)
    return websockets.serve(word_sender, host, port)
Ejemplo n.º 54
0
import asyncio
import websockets
from RPIO import PWM

servo1 = PWM.Servo()


async def updateMotor(websocket, path):
    valor = 0
    while (True):
        #Espera por nuevos datos
        potencia = await websocket.recv()

        #cuando hay un cambio, lo muestra por consola
        print("Potencia: " + potencia + "%")

        #actualiza la potencia del motor
        servo1.set_servo(26, 1000 + int(valor) * 10)


start_server = websockets.serve(updateMotor, '0', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 55
0
    rec = None
    while True:
        # retrieve request
        message = await websocket.recv()

        # create recognizer
        if not rec:
            rec = KaldiRecognizer(model, vosk_sample_rate)

        # run recognition in a thread
        response, stop = await loop.run_in_executor(pool, process_chunk, rec,
                                                    message)

        # send back response
        await websocket.send(response)

        # stop processing if signalled so by the client
        if stop:
            break


'''
Init and start socket server
'''
logger.info("Starting server on host " + vosk_interface + ", port " +
            str(vosk_port))
start_server = websockets.serve(recognize, vosk_interface, vosk_port)
loop.run_until_complete(start_server)
loop.run_forever()
Ejemplo n.º 56
0
import asyncio
import datetime
import random
import websockets
import cv2
import base64

cap = cv2.VideoCapture(0)


async def time(websocket, path):
    while True:
        ret, frame = cap.read()
        _, encoded_frame = cv2.imencode('.jpeg', frame)
        b64_payload = base64.b64encode(encoded_frame.tobytes()).decode('utf-8')
        await websocket.send(b64_payload)
        await asyncio.sleep(0.030)


start_server = websockets.serve(time, '10.20.0.160', 5678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 57
0
    reject_message = json.dumps({
        'type': 'reject',
        'user': username,
        'message': 'Username already in use',
        'userId': userId
    })
    await websocket.send(reject_message)


async def accept_username(username, userId):
    accept_message = json.dumps({
        'type': 'accepted',
        'user': username,
        'message': 'Username accepted',
        'userId': userId
    })
    await broadcast_message(accept_message)


async def listUsers():
    users = []
    for key in clients.keys():
        users.append(key)
    users_message = json.dumps({'type': 'users', 'message': users})
    print("Broadcasting:", users_message)
    await broadcast_message(users_message)


start_server = websockets.serve(receive_message, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 58
0
#!/usr/bin/env python

# WS echo server with HTTP endpoint at /health/

import asyncio
import http
import websockets


def health_check(path, request_headers):
    if path == '/health/':
        return http.HTTPStatus.OK, [], b'OK\n'


async def echo(websocket, path):
    async for message in websocket:
        await websocket.send(message)


start_server = websockets.serve(echo,
                                'localhost',
                                8765,
                                process_request=health_check)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 59
0
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--bind", help="IP address to bind to", default="")
    parser.add_argument("--port", help="TCP port", type=int, default=8000)
    parser.add_argument("--level", help="start on level", type=int, default=1)
    parser.add_argument("--seed", help="Seed number", type=int, default=0)
    parser.add_argument(
        "--timeout", help="Timeout after this amount of steps", type=int, default=TIMEOUT
    )
    parser.add_argument(
        "--grading-server",
        help="url of grading server",
        default="http://bomberman-aulas.ws.atnog.av.it.pt/game",
    )
    args = parser.parse_args()

    if args.seed > 0:
        random.seed(args.seed)

    g = GameServer(args.level, args.timeout, args.grading_server)

    game_loop_task = asyncio.ensure_future(g.mainloop())

    logger.info("Listenning @ %s:%s", args.bind, args.port)
    websocket_server = websockets.serve(g.incomming_handler, args.bind, args.port)

    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(websocket_server, game_loop_task))
    loop.close()
Ejemplo n.º 60
0
    async def send_2_clients(self, message: str):
        await asyncio.wait([client.send(message) for client in self.clients])

    async def distribute(self, ws: WebSocketServerProtocol):
        async for message in ws:
            if 'ignore' in message:
                logging.info('ignore response')
            elif 'double' in message:
                logging.info('double response')
                await self.send_2_clients(f'{message} #1')
                await self.send_2_clients(f'{message} #2')
            else:
                await self.send_2_clients(message)

    async def ws_handler(self, ws: WebSocketServerProtocol, uri: str):
        await self.register(ws)
        try:
            await self.distribute(ws)
        finally:
            await self.unregister(ws)


server = Server()
start_srv = websockets.serve(server.ws_handler, 'localhost', 4000)
loop1 = asyncio.get_event_loop()
loop2 = asyncio.get_event_loop()
loop1.run_until_complete(start_srv)
loop2.run_until_complete(server.periodic_message(5))
loop1.run_forever()
loop2.run_forever()