本文整理匯總了Python中websockets.serve方法的典型用法代碼示例。如果您正苦於以下問題:Python websockets.serve方法的具體用法?Python websockets.serve怎麽用?Python websockets.serve使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類websockets
的用法示例。
在下文中一共展示了websockets.serve方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: on_connect
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def on_connect(self, ws, client_id) -> tuple:
"""create a websocket server object connected to port"""
try:
port = self.available_ports.pop()
logger.debug(f"Selected port {port}")
except:
logger.warning("No more ports available")
await ws.send(json.dumps({"result": False}))
return
try:
server = await websockets.serve(
self.update_handler, device_ip, port)
logger.info(f"Server created for '{client_id}' on port {port}")
await ws.send(json.dumps({"result": port}))
return server, port
except:
logger.critical(f"Failed to create server for client '{client_id}'")
await ws.send(json.dumps({"port":False}))
示例2: run
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def run():
mp = None
if config["MAIL"]["START_MAILER"]:
mp = Popen(['python3', mailer])
try:
start_server = websockets.serve(server.server, config["SERVER"]["INTERFACE"], config["SERVER"]["PORT"])
if config["SERVER"]["RELOAD_ON_CHANGE"]:
asyncio.async(reloader(mp))
loop = asyncio.get_event_loop()
asyncio.async(start_server)
if config["IPN"]["START_IPN_SERVER"]:
asyncio.async(ipn.init(loop))
ext = config["SERVER"].get("EXT", None)
if ext is not None:
load_extensions(ext)
loop.run_forever()
finally:
if mp is not None:
mp.terminate()
示例3: start
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def start(self):
"""Start the server"""
# Secure behavior: adds a secure layer applying cryptography and authentication
if not (self.cert_path is None) and not (self.key_path is None):
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain(self.cert_path, self.key_path)
start_server = websockets.serve(
self._handler,
self.host,
self.port,
ssl=ssl_context,
max_size=None,
ping_timeout=None,
close_timeout=None,
)
else:
# Insecure
start_server = websockets.serve(
self._handler,
self.host,
self.port,
max_size=None,
ping_timeout=None,
close_timeout=None,
)
asyncio.get_event_loop().run_until_complete(start_server)
print("Serving. Press CTRL-C to stop.")
try:
asyncio.get_event_loop().run_forever()
except KeyboardInterrupt:
logging.info("Websocket server stopped.")
示例4: run_realtime
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def run_realtime(cls):
event_loop = asyncio.new_event_loop()
asyncio.set_event_loop(event_loop) # required by asyncio_redis
userlog_settings = util.get_userlog_settings()
uri = websockets.parse_uri(userlog_settings.websocket_address)
start_server = websockets.serve(
realtime.userlog, uri.host, uri.port, loop=event_loop)
stop_server = asyncio.Future(loop=event_loop)
cls.stop_realtime_server = lambda: event_loop.call_soon_threadsafe(
lambda: stop_server.set_result(True))
realtime_server = event_loop.run_until_complete(start_server)
event_loop.run_until_complete(stop_server)
realtime_server.close()
event_loop.run_until_complete(realtime_server.wait_closed())
event_loop.close()
示例5: start
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def start(self):
self.log.info("Starting Daemon Server")
def master_close_cb():
asyncio.ensure_future(self.stop())
try:
asyncio.get_running_loop().add_signal_handler(
signal.SIGINT, master_close_cb
)
asyncio.get_running_loop().add_signal_handler(
signal.SIGTERM, master_close_cb
)
except NotImplementedError:
self.log.info("Not implemented")
self.websocket_server = await websockets.serve(
self.safe_handle, "localhost", 55400
)
self.log.info("Waiting Daemon WebSocketServer closure")
print("Daemon server started", flush=True)
await self.websocket_server.wait_closed()
self.log.info("Daemon WebSocketServer closed")
示例6: start_websocket_server
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def start_websocket_server(open_port):
event_loop = asyncio.new_event_loop()
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()
thd = Thread(target=run_server)
thd.start()
try:
yield
finally:
event_loop.call_soon_threadsafe(event_loop.stop)
示例7: serve
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def serve(ws, path):
cluster_name = await ws.recv()
cluster_name = cluster_name.decode()
if cluster_name in CLIENTS:
print(f"! Cluster[{cluster_name}] attempted reconnection")
await ws.close(4029, "already connected")
return
CLIENTS[cluster_name] = ws
try:
await ws.send(b'{"status":"ok"}')
print(f'$ Cluster[{cluster_name}] connected successfully')
async for msg in ws:
print(f'< Cluster[{cluster_name}]: {msg}')
await dispatch(msg)
finally:
CLIENTS.pop(cluster_name)
print(f'$ Cluster[{cluster_name}] disconnected')
示例8: initialize_web
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def initialize_web():
ws = websockets.serve(send_message, global_settings.cfg[C_WEB_SETTINGS][P_WEB_IP], int(global_settings.cfg[C_WEB_SETTINGS][P_WEB_SOCK_PORT]),
origins=None)
asyncio.get_event_loop().run_until_complete(ws)
global_settings.socket_server = Thread(target=asyncio.get_event_loop().run_forever, daemon=True)
global_settings.socket_server.start()
rprint("Initialized Socket Server.", origin=L_WEB_INTERFACE)
log(INFO, "Initialized Socket Server", origin=L_WEB_INTERFACE)
global_settings.flask_server = Thread(target=start_flask_server, daemon=True)
global_settings.flask_server.start()
rprint("Initialized Flask Server.", origin=L_WEB_INTERFACE)
log(INFO, "Initialized Flask Server", origin=L_WEB_INTERFACE)
示例9: main
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def main():
c_source = asn1tools.compile_files([
'asn1/c_source.asn',
'asn1/programming_types.asn'
], 'oer')
start_server = websockets.serve(
functools.partial(echo, c_source=c_source),
'localhost',
8765)
print('Listening for websocket clients on localhost:8765...')
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
示例10: start
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def start(self):
web_socket = self.get_config('app.contact.websocket')
try:
await websockets.serve(self.handler.handle, *web_socket.split(':'))
except OSError as e:
self.log.error("WebSocket error: {}".format(e))
示例11: start
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def start(self):
start_server = websockets.serve(self.__handle, self.host, self.port)
self.loop.run_until_complete(start_server)
示例12: launch
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def launch(self, port, message_max_size):
event_loop = asyncio.get_event_loop()
start_server = websockets.serve(
self._handler, port=port, max_size=message_max_size)
self._server = event_loop.run_until_complete(start_server)
self._start_event.set()
event_loop.run_forever()
示例13: _create_server
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def _create_server(self, local_addr, sock):
async def hello(websocket, path):
proto = WS(app=self._app, loop=self._loop,
local_addr=local_addr,
peer_addr=websocket.remote_address,
websocket=websocket)
await proto.websocket_pump
try:
return self._servers[local_addr]
except KeyError:
server = await websockets.serve(hello, local_addr[0], local_addr[1],
subprotocols=['sip'])
self._servers[local_addr] = server
return server
示例14: serve
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def serve(self):
return websockets.serve(self.handle_client, self.host, self.port)
示例15: run_server
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import serve [as 別名]
def run_server(gimbal, **kw):
server = SocketServer(gimbal, **kw)
loop = asyncio.get_event_loop()
loop.run_until_complete(server.serve())
print("Server running at %s" % server.uri())
loop.run_forever()