I have java application running on Tomcat server. It works normally with Android/iOS/Web application. After logged in using username and password, the server will generate a token and the application use the token to establish websocket connection with server to receive and send message from/to server.
To receive a broadcast from the server, the application need to send a message to the server telling message code they want to subscribe.
Now, I want to implement python (version 3.9.6) application to receive and send message from/to the server. To make it easy in the first place, I skip the logged in process by logged in using postman and hard-coded token.
In the first try, I use library websockets
import asyncio
import websockets
# Define the WebSocket URL
async def connect_and_listen(url, headers):
print("called connect_and_listen")
async with websockets.connect(url, extra_headers=headers) as websocket:
print("called websockets.connect")
# Send Subscribe
try:
await websocket.send("A_BINARY_MESSAGE")
except Exception as e:
print(e)
print("while true")
# Loop Receive Broadcast
while True:
# Receive data from the WebSocket server
data = await websocket.recv()
# Update Excel with the received data using PyXLL functions
update_excel(data)
def update_excel(data):
print(data)
url = "ws://localhost:8080/BCST_PATH"
token = "TOKEN"
auth_token = "Bearer " + token
headers = {"Authorization": auth_token}
asyncio.get_event_loop().run_until_complete(connect_and_listen(url, headers))
The result is I did not receive any broadcast from server. So I decided to change library to websocket-client
import websocket
url = "ws://localhost:8080/BCST_PATH"
token = "TOKEN"
auth_token = "Bearer " + token
headers = {"Authorization": auth_token}
ws = websocket.WebSocket()
ws.connect(url, header=headers)
ws.send("A_BINARY_MESSAGE")
print ("Receiving...")
resp = ws.recv()
print ("Receive: %s", resp)
ws.close()
Still not working. I debugged in the Java application and it does not receive any message from client (both case).
I tried the same flow with the same url, token, and binary message using Postman and it works. I am out of idea what's wrong in my code.
Finally I found the solution. I use the 2nd code which using websocket-client
library. Adding websocket.ABNF.OPCODE.BINARY
makes it works!
ws.send("A_BINARY_MESSAGE", websocket.ABNF.OPCODE_BINARY)