Callback after websocket message is sent

problem description

example: get the return value in time after sending the login request, and then handle the next event according to the return value, similar to the http request, but the requirement is to do this with websocket.

in the introduction to websocket, we can fully realize that all callback functions of websocket are executed asynchronously, that is, after I send send (msg), I read the information in onmessage (), which obviously does not meet our requirements.

I want this effect

ws.send("",(res)=>{
    //ressendresponse
})


Jun.23,2022

I can only show you simply. Because the company's protection system cannot copy the code, I can only take a screenshot to show you. I encapsulated a websocket service of my own business system

.

clipboard.png

clipboard.png

clipboard.png

clipboard.png

clipboard.png


The problem with

is that

  1. if you want client to send a request, server must have a response corresponding to it, then you don't need websocket at all, or use http for this part and websocket for the rest.
  2. if you want client and server to send data in both directions, there is no guarantee that send will be followed by the result you want the server to return. You are send and server may not have received it at all.

it's not an implementation problem, it's a design problem.


       // websocket
       ws = new WebSocket("ws://xxx:xxx");
       // socket
       ws.onopen = onopen;
       // 
       ws.onmessage = onmessage; 
       ws.onclose = function() {
          console.log("");
          connect();
       };
       ws.onerror = function() {
           console.log("");
       };

there is a way to send a message at the beginning.

ws.onopen

of course, this may not solve your problem. But here is an example of a PHP chat room framework. The js section can be used for reference.

https://github.com/walkor/wor...


http one-way protocol. Ws is bidirectional. If these two requests want to get the return information from the server, don't they both have to wait for each other to respond before triggering a callback?
it's just that ws binds the callback to the onmessage of the ws instance.

Menu