Python中Websocket响应后自动关闭

use*_*858 5 python websocket python-3.x

以下代码作为服务器和浏览器客户端连接运行。然而,每次请求后,浏览器都会显示 websocket 连接已关闭。我想在浏览器客户端中保持连接打开,因为重新打开会因网络问题等而变慢。早期使用 Nodejs websocket 服务器时,它从未关闭连接。

谁能告诉我套接字可能在哪里以及如何关闭:

# WSS (WS over TLS) server example, with a self-signed certificate


from common import *
from datetime import datetime

import numpy as np
import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from pathlib import Path
import re
import time
import os.path
from dateutil.relativedelta import relativedelta

now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("Started time=", dt_string)

def decode_batch_predictions(pred):
    input_len = np.ones(pred.shape[0]) * pred.shape[1]
    # Use greedy search. For complex tasks, you can use beam search
    results = keras.backend.ctc_decode(pred, input_length=input_len, greedy=True)[0][0][
              :, :8
              ]
    # Iterate over the results and get back the text
    output_text = []
    for res in results:
        condition = tf.less(res, 0)
        res = tf.where(condition, 1, res)
        res = tf.strings.reduce_join(num_to_char(res)).numpy().decode("utf-8")
        output_text.append(res)
    return output_text


characters = [' ', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
              'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S',
              'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

characters = np.asarray(characters, dtype='<U1')
num_to_char = layers.StringLookup(
    vocabulary=characters, mask_token=None, invert=True
)

prediction_model = tf.keras.models.load_model('model_prediction2')
opt = keras.optimizers.Adam()
prediction_model.compile(optimizer=opt)

gg_hashmap = None

frameinfo = getframeinfo(currentframe())

async def hello(websocket, path):
    global gg_hashmap

    print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

    json_data = await websocket.recv()

    obj = json.loads(json_data)
    #print(obj, flush=True)


    if ("l" in obj and obj["l"]=='license'):


        res = {
            'status': 1,
            'python': 1,

        }



        json_string = json.dumps(res)

        await websocket.send(json.dumps(json_string))
    else:
        print("In else pat")


def start_server():
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)

    ssl_context.load_cert_chain("bundle.pem", "key.pem");

    ip = ''

    if os.name == 'nt':
        ip = '127.0.0.1'
    else:
        ip = "0.0.0.0"

    start_server = websockets.serve(
        hello, ip, 31334, ssl=ssl_context
    )

    asyncio.get_event_loop().run_until_compaserver.pyplete(start_server)
    asyncio.get_event_loop().run_forever()


def main():
    print("Entered main")
    global gg_hashmap
    gg_hashmap = getHash();
    start_server()
    print("Server started")




main()
Run Code Online (Sandbox Code Playgroud)

Von*_*onC 2

您编写的代码没有显式关闭 WebSocket 连接。websockets在使用库的典型 Python WebSocket 服务器实现中,WebSocket 连接保持打开状态,除非服务器或客户端显式关闭,或者除非发生未处理的异常导致协程(在本例中为函数hello)退出。

\n

在您的情况下,我将检查是否存在终止hello协程的异常,这将有效地关闭 WebSocket 连接。

\n

添加异常处理和日志记录可以帮助您确定是否是这种情况,包括如try except bloc所评论的那样。

\n
async def hello(websocket, path):\n    try:\n        global gg_hashmap\n        print(datetime.now().strftime(\'%Y-%m-%d %H:%M:%S\'))\n\n        json_data = await websocket.recv()\n        # rest of your code...\n    except Exception as e:\n        print(f"Exception occurred: {e}")\n
Run Code Online (Sandbox Code Playgroud)\n
\n

另请检查websockets 库常见问题解答,例如:

\n

这包括:

\n
\n

当处理程序退出时,websockets 负责关闭连接

\n
\n

在库的上下文中websockets,“处理程序”指的是处理 WebSocket 连接的协程\xe2\x80\x94(在您的情况下),即函数hello。如果此函数因任何原因退出,WebSocket 库将自动关闭相应的 WebSocket 连接。

\n

在现有代码中,该hello函数没有循环来保持其运行并连续侦听消息。一旦它接收到消息并处理它,该函数就会到达末尾,这将导致 WebSocket 库关闭连接。

\n

为了保持连接打开,您可以在内部引入一个循环hello,继续侦听传入的消息。例如:

\n
async def hello(websocket, path):\n    try:\n        global gg_hashmap\n\n        while True:  # Loop to keep the connection open\n            print(datetime.now().strftime(\'%Y-%m-%d %H:%M:%S\'))\n\n            json_data = await websocket.recv()\n\n            # Your existing code...\n            await websocket.send(json.dumps(json_string))\n\n    except ConnectionClosedError as e:\n        print(f"Connection closed unexpectedly: {e}")\n\n    except Exception as e:\n        print(f"An unexpected error occurred: {e}")\n
Run Code Online (Sandbox Code Playgroud)\n

添加while True循环将使处理程序保持运行,使 WebSocket 连接保持打开状态,直到收到显式关闭请求或发生异常。

\n