Synchronous request with Websockets

前端 未结 5 2087
一生所求
一生所求 2020-12-30 04:04

I can send and receive messages from server on websockets. I need to write a function that will send data to the server and is awaiting a response from the server and then r

5条回答
  •  -上瘾入骨i
    2020-12-30 04:30

    You should use some sort of RPC protocol on top of WebSockets. I suggest you take a look at WAMP which is a WebSocket sub-protocol that adds RPC and PUB/SUB semantics. It includes a client library which abstracts the async connection to some extent by giving you a promise based API.

    Here is an example:

    var wsuri = "ws://localhost:9000";
    
    ab.connect(wsuri, function (session) {
        session.call("http://example.com/simple/calc#add", 23, 7).then(
            function (res) {
                console.log("got result: " + res);
            },
            function (error, desc) {
                console.log("error: " + desc);
            }
        );
    });
    

    There are a number of server-side implementations for this.

提交回复
热议问题