PeerToPeer - element-ts/lithium GitHub Wiki
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.
- Create a new
LiCommandRegistryStructurefor "Sibling Commands" and pass it as the third type parameter inLiSocket.init(). - Add the
alllowPeerToPeerproperty to the configuration object passed toLiSocket.init()and set its value totrue. This property defaults tofalse. - Implement your new command with
implementSibling()instead ofimplement().
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
);- If the sibling socket you are trying to invoke a command on does not have
allowPeerToPeerset totruein its config, the invocation will error out even if the sibling has the method implemented. - The server marks methods as
peerToPeerwhen 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
implementSiblingand notimplement. TheimplementSiblingmethod internally calls implement, but it also marks the command as a command that is allowed to be called via a sibling.