Answer the question
In order to leave comments, you need to log in
Is there a websocket plugin for Vue that allows you to get the server response after sending a message directly?
I'm using vue-native-websocket and just realized that it uses to send a message $socket.send(message)
and to receive
this.$options.sockets.onmessage = (data) => console.log(data)
. setTimeout
using is not an option, since you will never guess whether the set time is enough to receive a response or not (after all, the number of users connected to the server will always be different), and throwing time with a margin for a timeout is wrong, because if the data is loaded, the extra time is just nothing does not happen (and 1 problem does not go anywhere). Answer the question
In order to leave comments, you need to log in
What does it mean to "get the answer directly"? Websockets - asynchronous communication. There is no "request-response" principle here. You can make such behavior on them, as well as on any asynchronous communication, using the correlation id.
For example, you send a message to the server with data
{"request": {"x": 123, "y": 123.45}, "id": "1234567"}
, where id must be fairly unique within the websocket. For example, a sequence of natural numbers. {"response": {"x": 321, "y": 45.321}, "id": "1234567"}
class WSHandler {
constructor(ws) {
this.ws = ws;
this.sequence = 0;
this.waiters = {};
}
onMessage(event) {
const { data } = event;
const { id } = data;
if (!this.waiters[id]) {
throw new Error(`No waiter for response #${id} was found`);
}
this.waiters[id](data.response);
delete this.waiters[id];
}
sendRequest(requestData) {
const id = this.sequence++
const msg = {id, request: requestData};
this.ws.send(msg);
return new Promise(resolve => {
this.waiters[id] = resolve;
});
}
}
...
const handler = new WSHandler(new WebSocket('wss://...'));
const response = await handler.sendRequest({"hello": "world"});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question