Websocket automatically closes after response in Python

The following code is run as a server and browser clients connect.
However after each request the browser is showing that websocket connection is closed. I want to keep connection open in browser clients as reopening is making it slow due to network issues etc.
Earlier with Nodejs websocket servers it never closed the connections.

Can anybody tell me where and how socket may be getting closed:

# 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()

  • Did you try to add error handling to the hello() method? add a try except block around the websocket.recv() and send() with websockets.exceptions.ConnectionClosedError and check what the output might be to at least provide better context to the issue.

    – 

  • I’m a beginner with Python. I guess some silly issue i’m missing

    – 

Leave a Comment