Esempio n. 1
0
async def main():
    # Set the stop condition when receiving SIGTERM.
    loop = asyncio.get_running_loop()
    stop = loop.create_future()
    loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)

    async with websockets.unix_serve(
        echo,
        path=f"{os.environ['SUPERVISOR_PROCESS_NAME']}.sock",
    ):
        await stop
Esempio n. 2
0
 async def serve(self):
     LISTEN_FDS: int = int(os.getenv("LISTEN_FDS", 0))
     if LISTEN_FDS > 0:  # file descriptor(s) passed by the service manager
         if LISTEN_FDS > 1:
             raise ValueError(
                 f"More than one ({LISTEN_FDS}) file descriptor was passed by the service manager"
             )
         SD_LISTEN_FDS_START: int = 3
         sock: socket.socket = socket.socket(fileno=SD_LISTEN_FDS_START)
         async with websockets.unix_serve(
             self._handler,
             path=None,
             sock=sock,
             create_protocol=protocol.ServerProtocol,
             subprotocols=["game", "match"],
         ):
             logger.info(f"Running on {sock.getsockname()}")
             await self._shutdown
     elif config.UNIX_SOCKET is not None:
         async with websockets.unix_serve(
             self._handler,
             config.UNIX_SOCKET,
             create_protocol=protocol.ServerProtocol,
             subprotocols=["game", "match"],
         ):
             logger.info(f"Running on {config.UNIX_SOCKET} (Press CTRL+C to quit)")
             await self._shutdown
     else:
         async with websockets.serve(
             self._handler,
             "localhost",
             config.PORT,
             create_protocol=protocol.ServerProtocol,
             reuse_port=config.REUSE_PORT,
             subprotocols=["game", "match"],
         ):
             logger.info(
                 f"Running on localhost:{config.PORT} (Press CTRL+C to quit)"
             )
             await self._shutdown
     logger.info("Server stopped")
Esempio n. 3
0
def main():
    global cipher, normal_dns,loc

    parser = argparse.ArgumentParser(description="Server part for crossing the GFW")
    parser.add_argument('-c', '--config', help="config file", default='config.json')
    parser.add_argument('-d', '--debug', help='enable debug output', default=False, action='store_true')
    args = parser.parse_args()

    level = logging.DEBUG if args.debug else logging.INFO
    logging.basicConfig(level=level,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%H:%M:%S')

    with open(args.config) as f:
        config = json.load(f)


    if config['mode'] == "replace":
        cipher = Replace()
        cipher.load_key(config['key'])
    elif config['mode'] == 'aes-128-gcm':
        cipher = AES_128_GCM()
        cipher.load_key(config['key'])
    elif config['mode'] == "none":
        cipher = NoEncrypt()
    else:
        print("Unsupported mode",file=sys.stderr)
    try:
        ssl_context = ssl.SSLContext()
        ssl_context.load_cert_chain(config['ssl_server_pem'], keyfile=config['ssl_server_key'])
    except KeyError:
        ssl_context = None

    setEnableCompression(config.pop('compress', True))

    loc = config.pop('loc',None)

    global enable_dns_relay
    enable_dns_relay = config.pop('dnsrelay',False)
    normal_dns = config.pop('normal_dns','8.8.8.8')

    loop = asyncio.get_event_loop()


    if "unix_socket_path" in config:
        asyncio.ensure_future(websockets.unix_serve(new_ws_connection,config['unix_socket_path']))
    else:
        asyncio.ensure_future(websockets.serve(new_ws_connection,
                                           config["serverAddress"], config["serverPort"],ssl=ssl_context))


    loop.run_forever()
Esempio n. 4
0
async def main():
    socket_path = os.path.join(os.path.dirname(__file__), "socket")
    async with websockets.unix_serve(hello, socket_path):
        await asyncio.Future()  # run forever
Esempio n. 5
0
import asyncio
import os.path
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}")


socket_path = os.path.join(os.path.dirname(__file__), "socket")
start_server = websockets.unix_serve(hello, socket_path)

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