WebSocket request-response subprotocol

The WebSocket Application Messaging Protocol (WAMP) https://wamp-proto.org/ provides RPC (Remote Procedure Call) and PubSub (Publish & Subscribe) messaging patterns on top of raw WebSocket for that purpose.

WAMP is a proper WebSocket subprotocol, uses WebSocket as transport and JSON as a payload format. RPC is implemented using 3 messages, and those messages contain a "Call ID" to correlate asynchronous RPC server responses to client initiated procedure calls.

Disclaimer: I am author of WAMP and some (open-source) WAMP implementations. Its an open initiative, with others already started to get on the boat. Ultimately, there should be a WAMP RFC properly defining the protocol .. but its still in the early stages.


I would use JSON-RPC 2.0.

http://www.jsonrpc.org/specification

Each message would be a JSON object. The protocol states if it is a call that wants a response (coupling with id), or a notification.

A JSON-RPC aware application could easily check if the message object contains a method, signifying a call, or not, signifying a response.

I'm about to build a javascript lib to handle json rpc over websocket, with ajax as fallback…


(send a id with the request and wait for a reponse with the same id until a timeout period)

I created a lib that does exactly that, called WebSocketR2 (where R2 means Request Response): https://github.com/ModernEdgeSoftware/WebSocketR2

It also handles reconnecting to the server if a connection is lost, which could be helpful if you are doing web sockets through a load balancer.

The final result is you can implement callbacks on the web socket send function like this:

var request = {
    action: "login",
    params: {
        username: "test",
        password: "password"
    }
};

ws.send(request, function(response){
    console.log(response)
});

Take a look at msg-rpc, it provides bidirectional rpc support over simple message interface, include WebSocket.

Not only the simple rpc, which could cover "client request / server response" behavior, it also supports "server request / client response" behavior, which is via the Rpc Service.

To get start with, there're sockjs and socket.io examples .