Jupyter notebook websocket recv error: socket is already closed

I try to create session in jupyter notebook and execute code with jupyter notebook API, the code is as follows:

  url = base + '/api/sessions'
    params = '{"path":\"%s\","type":"notebook","name":"","kernel":{"id":null,"name":"env37"}}' % file_name
    response = requests.post(url, headers=headers, data=params)
    session = json.loads(response.text)
    kernel = session["kernel"]

    # 讀取notebook檔案,並獲取每個Cell裡的Code
    url = base + '/api/contents' + notebook_path
    response = requests.get(url, headers=headers)
    file = json.loads(response.text)
    code = [c['source'] for c in file['content']['cells'] if len(c['source']) > 0]
    ws = create_connection("ws://127.0.0.1:8888/api/kernels/" + kernel["id"] + "/channels?session_id" + session["id"],
                           header=headers)
    for c in code:
        ws.send(json.dumps(send_execute_request(c)))

    # 我們只拿Code執行完的訊息結果,其他訊息將被忽略
    for i in range(0, len(code)):
        try:
            msg_type = ''
            while True:
                rsp = json.loads(ws.recv())
                msg_type = rsp["msg_type"]

I try to create session in jupyter notebook and execute code with jupyter notebook API, the code is as follows:

    url = base + '/api/sessions'
    params = '{"path":\"%s\","type":"notebook","name":"","kernel":{"id":null,"name":"env37"}}' % file_name
    response = requests.post(url, headers=headers, data=params)
    session = json.loads(response.text)
    kernel = session["kernel"]

    # 讀取notebook檔案,並獲取每個Cell裡的Code
    url = base + '/api/contents' + notebook_path
    response = requests.get(url, headers=headers)
    file = json.loads(response.text)
    code = [c['source'] for c in file['content']['cells'] if len(c['source']) > 0]
    ws = create_connection("ws://127.0.0.1:8888/api/kernels/" + kernel["id"] + "/channels?session_id" + session["id"],
                           header=headers)
    for c in code:
        ws.send(json.dumps(send_execute_request(c)))

    # 我們只拿Code執行完的訊息結果,其他訊息將被忽略
    for i in range(0, len(code)):
        try:
            msg_type = ''
            while True:
                rsp = json.loads(ws.recv())
                msg_type = rsp["msg_type"]

but in “ws.recv()”, there is an error: raise WebSocketConnectionClosedException(“socket is already closed.”)

and the jupyter notebook cmd shows:

[I 18:04:05.904 NotebookApp] Kernel started: 275c3afd-cc10-4a69-8597-9f0d7f3e3a91, name: env37
[W 18:04:05.913 NotebookApp] Notebook example2.ipynb is not trusted
[W 18:04:05.917 NotebookApp] No session ID specified
[W 18:04:07.473 NotebookApp] No channel specified, assuming shell: {'header': {'msg_id': '9f4ce706980c11eebfe64ed5776c682d', 'username': 'test', 'session': '9f4cfa28980c11ee92b64ed5776c682d', 'data': '2023-12-11T18:04:07.471569', 'msg_type': 'execute_request', 'version': '5.0'}, 'parent_header': {'msg_id': '9f4ce706980c11eebfe64ed5776c682d', 'username': 'test', 'session': '9f4cfa28980c11ee92b64ed5776c682d', 'data': '2023-12-11T18:04:07.471569', 'msg_type': 'execute_request', 'version': '5.0'}, 'metadata': {}, 'content': {'code': 'from resync import resync', 'silent': False}}
[W 18:04:07.474 NotebookApp] No channel specified, assuming shell: {'header': {'msg_id': '9f4cfa29980c11eea45e4ed5776c682d', 'username': 'test', 'session': '9f4cfa2a980c11eebef84ed5776c682d', 'data': '2023-12-11T18:04:07.471569', 'msg_type': 'execute_request', 'version': '5.0'}, 'parent_header': {'msg_id': '9f4cfa29980c11eea45e4ed5776c682d', 'username': 'test', 'session': '9f4cfa2a980c11eebef84ed5776c682d', 'data': '2023-12-11T18:04:07.471569', 'msg_type': 'execute_request', 'version': '5.0'}, 'metadata': {}, 'content': {'code': '...', 'silent': False}}
[I 18:04:07.481 NotebookApp] Starting buffering for 275c3afd-cc10-4a69-8597-9f0d7f3e3a91:016c7619-9a09e6bff5dcdcab49729795

when I shutdown the kernel env37 in my jupyter notebook UI, it shows:

[I 18:04:51.838 NotebookApp] Discarding 10 buffered messages for 275c3afd-cc10-4a69-8597-9f0d7f3e3a91:016c7619-9a09e6bff5dcdcab49729795
[I 18:04:51.838 NotebookApp] Kernel shutdown: 275c3afd-cc10-4a69-8597-9f0d7f3e3a91

I guess it is that the websocket was closed before the reply was sent, but why and how could it be solved?
(this question is also posted on stackoverflow

Please note cross-posts in all places you make them so that those trying to help you don’t waste time saying something already covered elsewhere. This also helps others with the same issue find appropriate discussion & solutions.

2 Likes

Thank you, I hace edited the question and add the cross posts

It is solved by reconnection to the server with create_connection and the same params.Note that the timezone has to be specified in the message’s ‘data’ part.Now it can receive the server’s reply.

1 Like