Now, I am writing a program that uses websocket to get messages and process them each time.

I would like to add a variable to the argument of on_message as shown below. Is it possible?

def on_message (ws, message, signal):

In the first place, as a basis of programming using websocket, I feel that it is better not to do complicated processing in def on_message, but I could not find any other method.
If anyone knows a good way, please let me know.

import sys
import websocket
import _thread
def on_message (ws, message):
    # Now we are processing the message in this function.
    print ('--- RECV MSG. ---')
    print (message)
def on_error (ws, error):
    print ('--- ERROR ---')
    print (error)
def on_close (ws):
    print ('--- DISCONNECTED ---')
def on_open (ws):
    print ('--- CONNECTED ---')
    def run (* args):
        while (True):
            line = sys.stdin.readline ()
            if line! ='':
                print ('closing ...')
                ws.close ()
    _thread.start_new_thread (run, ())
url ='ws: // *****/****/websocket'
# websocket.enableTrace (True)
ws = websocket.WebSocketApp (url,
                          on_message = on_message,
                          on_error = on_error,
                          on_close = on_close)
ws.on_open = on_open
ws.run_forever ()
  • Answer # 1

    As the questioner feels, it is annoying to write a program elegantly that keeps the websocket connected and processes the incoming message. Since on_message is specified in the library as a callback, you probably can't add an argument. Also, although it is not decided not to write complicated processing in on_message, it feels like a place to write complicated processing somehow.

    In the previous question and answer, I tried to challenge such a request, and I think it will be helpful.
    The communication process of websocket is well hidden in the class so that only the message can be processed on the main function side. Please forgive that the description of async/await is a little noisy. Based on this code, I think it will be easier for the questioner to write the code he wants to write.

    Please note that there is a library with a misleading name called websockets, which is used.

Related articles