Establishing a JSON-RPC connection
Transports
A JSON-RPC connection communicates over an existing transport, such as HTTP, Sockets and pipes, and Websockets:
- HTTP POST: unidirectional, one request/response pair per call.
- Sockets and pipes, via chronos'
StreamTransport: bidirectional, persistent connection, custom message framing.Framing.httpHeader:Content-Lengthprefix specifying the length of the payload, compatible with vscode-jsonrpc.Framing.lengthHeaderBE32: Big-endian, 32-bit binary prefix - most efficient option.
- Websockets: bidirectional, persistent connection.
Server (and possibly client also)
Create the server instance using one of the available transports:
HTTP:
let srv = newRpcHttpServer(["127.0.0.1:0"])
Sockets:
const framing = Framing.lengthHeaderBE32()
let srv = newRpcSocketServer(["127.0.0.1:0"], framing = framing)
Websockets:
let srv = newRpcWebSocketServer("127.0.0.1", Port(0))
After registering the RPC methods, the server can start serving clients:
srv.start()
Then usually runForever() or waitFor a program termination signal waitSignal(SIGINT). This will run the Chronos async event loop until the program is terminated.
Client
Create the client instance using one of the available transports:
HTTP:
let client = newRpcHttpClient()
await client.connect("http://" & $srv.localAddress()[0])
Sockets:
const framing = Framing.lengthHeaderBE32()
let client = newRpcSocketClient(framing = framing)
await client.connect(srv.localAddress()[0])
Websockets:
let client = newRpcWebSocketClient()
await client.connect("ws://" & $srv.localAddress())
You can then proceed to send requests.
Disconnecting
Close the client connection:
await client.close()
Stop the RPC server and clean-up resources:
await srv.stop()
await srv.closeWait()