Skip to content

Instantly share code, notes, and snippets.

@cosimo
Created August 29, 2023 08:44
Show Gist options
  • Save cosimo/82e0ebd848e95a35c6a2462032ee2063 to your computer and use it in GitHub Desktop.
Save cosimo/82e0ebd848e95a35c6a2462032ee2063 to your computer and use it in GitHub Desktop.
Python: connect to a websocket and send a message without any asyncio complications
#
# Requirements:
# - websocket-client==1.6.2
#
from websocket import create_connection
def select_origin_header(extra_headers):
origin = None
headers_no_origin = []
for header in extra_headers:
if header.lower().startswith("origin:"):
origin = header.lower().replace("origin: ", "")
else:
headers_no_origin.append(header)
return origin, headers_no_origin
def wss_connect(ws_url, message="Hello", extra_headers=None):
# Needed to avoid sending the Origin HTTP header twice
origin, extra_headers = select_origin_header(extra_headers)
ws = create_connection(ws_url, timeout=3, header=extra_headers)
#print("<<<", ws.recv())
print(f"Sending message '{message}'")
ws.send(message)
result = ws.recv()
print(f"<<< Received '{result}'")
ws.close()
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment