Skip to content

PeerToPeer

Elijah Cobb edited this page Apr 20, 2020 · 3 revisions

Another really cool feature built right into Lithium is peer-to-peer command invocation. There are just a couple things you need to change to make a peer-to-peer command accessible.

  1. Create a new LiCommandRegistryStructure for "Sibling Commands" and pass it as the third type parameter in LiSocket.init().
  2. Add the alllowPeerToPeer property to the configuration object passed to LiSocket.init() and set its value to true. This property defaults to false.
  3. Implement your new command with implementSibling() instead of implement().

Example

interface SiblingCommands extends LiCommandRegistryStructure {
    getFavoriteNumber: {
        param: void;
        return: number;
    }
}
const socket: LiSocket<LC, RC, SiblingCommands> = await LiSocket.init({
    address: "ws://localhost:8080",
    debug: true,
    allowPeerToPeer: true
});

socket.implementSibling("getFavoriteNumber", async(): Promise<number> => {
    return 42;
});

With the above implementation, a different client could invoke this command. All you need is the id of the sibling socket. To get the id of a socket, call getId(). View below:

const favoriteNumber = await socket.invokeSibling(
    "id-of-the-sibling-socket",
    "getFavoriteNumber",
    undefined
);

Notes

  • If the sibling socket you are trying to invoke a command on does not have allowPeerToPeer set to true in its config, the invocation will error out even if the sibling has the method implemented.
  • The server marks methods as peerToPeer when a socket tries to invoke a command on a sibling. For more info on the internal protocol, view the Protocol page.
  • Make sure to use implementSibling and not implement. The implementSibling method internally calls implement, but it also marks the command as a command that is allowed to be called via a sibling.

Pages

element-ts

Element is a group of developer tools I have built in TypeScript. Check them out at: element-ts.com.

About

Author: Elijah Cobb

NPM: @element-ts/lithium

Issue Reporting: Github Issues

Clone this wiki locally