i'm writing a bridge between two servers and am puzzled on how to do it properly. I have a socketio server that sends me a message which i need to transform and reroute to a websocket.
Look at my first try:
import socketio
import asyncio
import websockets
the_socketio_adress = 'http://localhost:1234'
the_websocket_adress = 'ws://localhost:1235'
my_socketio_client = socketio.Client()
#THIS DOES NOT WORK
@my_socketio_client.on('message')
def on_message(data):
messageId = data['messageId']
value = data['value'] if 'value' in data else None
if messageId == "requiredTag":
event = {"sender":"myclients_name",messageId:value}
**websocket.send(json.dumps(event))**
#THIS DOES NOT WORK:END
my_socketio_client.connect(my_socketio_adress)
async def listen_to_websocket_server():
async with await websockets.connect(my_websocket_adress) as websocket:
while 1:
response = await websocket.recv()
response_dict = json.loads(response)
response_list = extract_values(response_dict, [], [])
for keyvaluepair in response_list:
my_socketio_client.emit('message_from_websocketserver', {'messageId':keyvaluepair[0], 'value':keyvaluepair[1]})
asyncio.run(listen_to_websocket_server())
I thought this might be a solution, but i don't understand how to use the websocket in the function on_message(data)
of my_socketio_client
or if this is even possible. The problem is, on_message(data)
gets called once upon an event, but i think it is not possible to use a running websocket in this function. The only solution i see is to always connect a new websocket upon on_message(data)
but this would be inefficient. Is there an option to use one websocket and assign it to a global variable or something, so i could recieve and send via the same websocket but in multiple functions?
afaik
websocket = websockets.connect(...)
does not work, because then websocket.recv()
says that a Connect
-Object does not have a recv method. Also afaik, a websocket needs to be async and can only be used in async functions, which on_message(data)
is not.
I was thinking about using a queue, but still, i need a websocket that recieves and sends in two different functions and don't want to use two websockets for that (because i don't even think this is possible due to the implementation of the server where my websocket connects to).
i already saw python-websocket-server-forwards-messages-from-other-websocket-server but they did not provide any solution