A
A
Artem Prokhorov2021-06-17 23:02:18
Vue.js
Artem Prokhorov, 2021-06-17 23:02:18

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)
.
And as if everything is transmitted, but in this, albeit scanty, but the interval, the code has time to be executed, which, as it were, should be executed only after receiving a response. setTimeoutusing 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).
I did not find anything about this in the use cases on the github repository.
If this can be achieved in vue-native-websocket, please tell me how.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2021-06-18
@deliro

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.
And you also expect the server to return the response with the same id. For example, like this:
{"response": {"x": 321, "y": 45.321}, "id": "1234567"}

In this case, you can do something like this:
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 question

Ask a Question

731 491 924 answers to any question