I have a node script that spawns a random number of websocket connection.
In that same script, I await a call to my server to ping the websockets to count the number of responses within a timeout.
The problem is that the await blocks the websocket's ability to respond and they only DO respond after the await is resolved (after some timeout).
How can I spawn websockets, await a request and NOT block the websockets in the same script?
const axios = require('axios');
const { io } = require('socket.io-client');
const sock = async ({_id}) => {
let socket = await io("ws://localhost:54321")
socket.on('connect',(args) => {
console.log(`${_id} connected to ws.`);
})
socket.on('ping',args => {
console.log("PING RECEIVED ("+_id+")")
socket.emit('pong',{socketId:_id,...args})
})
return socket;
}
(async function go(){
let g_sockets = [];
await Promise.all(['so0','s01'].map(async _id => {
let s = await sock({_id})
g_sockets.push(s);
}))
await new Promise((res,rej) => {
axios.get('http://localhost:54321/roomSize').then(r => {
console.log(r.data);
res(r.data)
})
})
})()
Here, the socket.on('ping',function) only fires AFTER the /roomSize HTTP request resolves, which means the /roomSize calculation is incorrect.
My Flask server route looks like:
ping_holder = {}
@app.route('/roomSize')
def getRoomSize():
pingId = str(random.randint(0,1e6))
ping_holder[ pingId ] = []
data = { "pingId":pingId }
socketio.emit('ping',data=data,broadcast=True)
time.sleep(1)
return jsonify(ping_holder[pingId])