4

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()
1
  • 1
    You could encode your binary data with base64 and transfer it as text. Commented Jun 7, 2020 at 17:18

3 Answers 3

7

Try this one:

ws.send(data, websocket.ABNF.OPCODE_BINARY)
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0

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

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.