Prim+RPC can communicate over WebSocket for easy support of callback defined on your methods. You may either use the
WebSockets alone as a callback handler with Prim+RPC (always upgrade HTTP to a WebSocket connection) or use both an HTTP
server (some method handler in Prim+RPC) and WebSocket server together, only upgrading to a WebSocket connection when
it’s actually needed: Prim+RPC will know when to do so. We’ll cover both scenarios:
In both cases, we’ll use the same module with Prim+RPC, which will simply type each letter of the message that we give
it over a callback:
module.ts
WebSocket Alone
You may use Prim+RPC with a WebSocket server only, if needed. In this case, all HTTP requests will be upgraded to a
WebSocket connection.
index.ts
Now we can test out using our function from the WebSocket server! We may either
set up the corresponding method plugin to test out WebSockets or use
command-line tools like wscat to test it out:
In this example, we’ll use a method handler that will communicate over HTTP alone and whenever a callback is given,
Prim+RPC will upgrade the connection to WebSocket.
First, we’ll set up some method handler with Prim+RPC. You may choose any server that you like. We’ll simply pass the
resulting server into ws when setting up the callback handler.
For example, let’s say that we have already set up Prim+RPC with Hono:
index.ts
We can add the callback handler to Prim+RPC by simply passing the server to ws. We can then pass our WebSocket server
to Prim+RPC’s callback handler like so:
When using the Prim+RPC client there is no need to understand the RPC structure but for testing with a generic WebSocket
client, you may need to know how Prim+RPC serializes callback data. Below is an example
session using wscat: