0

I've received the following error in my script on Websocket whilst trying to stream.

raise WebSocketConnectionClosedException("socket is already closed.") websocket._exceptions.WebSocketConnectionClosedException: socket is already closed.

I tried to code an exception to catch it and restart the websocket:

    except WebSocketConnectionClosedException as e:
        ws = opensocket()
        websocket_open = True
        data = "WebSocketConnectionClosedException trying to restart stream"
        send_email(data,recipient)
        print(e)

However, when I run it now, I get the following error:

Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev\pydevd.py", line 1668, in main() File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev\pydevd.py", line 1662, in main globals = debugger.run(setup['file'], None, None, is_module) File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev\pydevd.py", line 1072, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev_pydev_imps_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/Users/Bev/Documents/python_work/bot/l_stream2_3.py", line 1117, in except WebSocketConnectionClosedException as e: NameError: name 'WebSocketConnectionClosedException' is not defined

Question 1 : How do i define the error in order for the exception to catch the error

Question 2: Are there perhaps a better way to restart the socket if the host closes the connection, or if the stream dies?

2 Answers 2

2

So I figured it out.

import websocket

#<Code>

except websocket.WebSocketConnectionClosedException as e:
    print('This caught the exception')
Sign up to request clarification or add additional context in comments.

Comments

0

Think the proper way will be

from websocket import create_connection
from websocket._exceptions import WebSocketConnectionClosedException

ws=create_connection("wss://url")
while True:
    try:
        ws.recv()
    except WebSocketConnectionClosedException as e:
        #Triggered when connection is closed by server
        #Handle exception

Some common ways to handle will be to place the above in a function and recall that function when the exception is triggered. However it is better to follow the example here https://github.com/websocket-client/websocket-client if the connection is going to be long lived

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.