Exemple #1
0
async def is_websocket_active(ws: WebSocket) -> bool:
    if not (ws.application_state == WebSocketState.CONNECTED and ws.client_state == WebSocketState.CONNECTED):
        return False
    try:
        await asyncio.wait_for(ws.send_json({'type': 'ping'}), HEART_BEAT_INTERVAL)
        message = await asyncio.wait_for(ws.receive_json(), HEART_BEAT_INTERVAL)
        assert message['type'] == 'pong'
    except BaseException:  # asyncio.TimeoutError and ws.close()
        return False
    return True
def __send_message(websocket: WebSocket, message: str) -> None:
    """
    Send a text message to the given websocket

    Args:
        websocket: Client with will be messaged
        message: Message to be send
    """
    if websocket.client_state == WebSocketState.CONNECTED:
        asyncio.run(websocket.send_json({'data': message}))
def __send_img(websocket: WebSocket, image_path: str, final: bool) -> None:
    """
    Send a image to the given websocket

    Args:
        websocket: Client with will be messaged
        image_path: recursiv path, starting from the main directory
        final: is it the last image send?
    """
    data_to_send = base64.b64encode(
        load_img_to_bytes(image_path).getvalue()).decode('utf-8')
    data_to_send = 'data:image/png;base64,' + data_to_send

    if websocket.client_state == WebSocketState.CONNECTED:
        asyncio.run(websocket.send_json({
            'done': final,
            'image': data_to_send
        }))
def __send_gif(websocket: WebSocket, image_path: str, final: bool) -> None:
    """
    Send a gif to the given websocket

    Args:
        websocket: Client with will be messaged
        image_path: recursiv path, starting from the main directory
        final: is it the last image send?
    """
    with open(image_path, 'rb') as img_file:
        img = img_file.read()

        data_to_send = base64.b64encode(img).decode('utf-8')
        data_to_send = 'data:image/gif;base64,' + data_to_send

        if websocket.client_state == WebSocketState.CONNECTED:
            asyncio.run(
                websocket.send_json({
                    'done': final,
                    'image': data_to_send
                }))
Exemple #5
0
def _terminate(ws: WebSocket):
    ws.send_json({"type": "connection_terminate"})
Exemple #6
0
def _init(ws: WebSocket):
    ws.send_json({"type": "connection_init"})
    assert ws.receive_json() == {"type": "connection_ack"}
def _terminate(ws: WebSocket) -> None:
    ws.send_json({"type": "connection_terminate"})  # type: ignore
def _init(ws: WebSocket) -> None:
    ws.send_json({"type": "connection_init"})  # type: ignore
    assert ws.receive_json() == {"type": "connection_ack"}