How to send binary data with websocket client python use WebSocketApp (not create_connection)

Viewed 4278

I selected WebSocketApp because it can remain connected forever. Unfortunately WebSocketApp does not offer ws.send_binary() just like create_connection. I want send binary data message and decode incoming message, Please help me, here is the original example:

import websocket
def on_message(ws, message):
    print(message)
def on_error(ws, error):
    print(error)
def on_close(ws):
    print('Websocket: closed')
def on_open(ws):
    print('Websocket: open')
ws = websocket.WebSocketApp('ws://echo.websocket.org/',on_message = on_message,on_error = on_error,on_close = on_close,on_open = on_open)
ws.run_forever()
3 Answers

Try this one:

ws.send(data, websocket.ABNF.OPCODE_BINARY)

You could use websockets or ws4py(ws.send(buf, binary=True)), both can send binary data directly.

There are actually 2 ways to achieve this:

  1. Use websocket-client's create_connection method
from websocket import create_connection
ws = create_connection("ws://echo.websocket.org/")
print("Sending 'Hello, World'...")
ws.send_binary([100, 220, 130])
print("Sent")
print("Receiving...")
result =  ws.recv()
print("Received '%s'" % result)
ws.close()
  1. Use WebSocketApp of websocket-client
import _thread
import time

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws, close_status_code, close_msg):
    print("### closed ###")

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send(byte_data, websocket.ABNF.OPCODE_BINARY)
        time.sleep(1)
        ws.close()
        print("thread terminating...")
    _thread.start_new_thread(run, ())

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                              on_open=on_open,
                              on_message=on_message,
                              on_error=on_error,
                              on_close=on_close)

    ws.run_forever()
Related