Answer the question
In order to leave comments, you need to log in
What are the approaches for communicating over websockets?
I decided to implement a real-time application completely built on websockets. Before that, I had experience with RESTapi, RPC over HTTP, and the SocketIO library. If the RESTapi and RPC approaches are clear to me and there are a bunch of examples describing their advantages and disadvantages, then there is very little information on websockets.
I know that there is a SocketIO library that allows you to both send messages to the server-> client or client-> server, and has the ability to implement something like a request response (and all this can work on websockets). But I want to implement everything without this lib.
So what are the approaches for communicating over websockets?
Answer the question
In order to leave comments, you need to log in
Well, you develop a protocol and implement it.
The protocols that I did are arranged approximately according to the following scheme:
A multiplexer is placed on the WebSocket channels in both directions. The multiplexer distinguishes between new requests and responses to old ones.
The initiator of a new request generates a unique key by which he is going to wait for a response, and sends the key with the request. To handle new requests, a new asynchronous function (goroutine) is launched. When it's done, it sends the result with the given key.
To receive responses, the multiplexer on the JS side stores the wrong side of the promises (a tuple of the resolve and reject closures) in a map according to the request keys. When the multiplexer receives a response from the map by key, such an underside is extracted, and resolve or reject is called.
In JavaScript, therefore, an async function can make an await new Promise, with a function that stores the reverse side resolve&reject arguments in a multiplex map, sends a request, and such an expression in an async function will immediately return a response or an exception. The same is done in Go.
The result is a two-way RPC, called on both sides in a synchronous style. Figure out how to serialize/print arguments, and do it.
On the Go side, I would use a monitor as an analogue of a tuple of resolve and reject closures. The monitor protects a two-element or one-element object in which one cell is allocated for the future result and the second for the error, or they are combined. Such objects with monitors add up to a map with keys. There is a way, when receiving a response from JS, to put a value or an error in the monitor so that the condition variable works. The condition variable fires when something appears under the monitor's protection. Goroutines that want a response from JS put an object with a monitor in the map, send a request via WS and hang on waiting for a conditional variable.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question