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.
- Create a new
LiCommandRegistryStructure
for "Sibling Commands" and pass it as the third type parameter inLiSocket.init()
. - Add the
alllowPeerToPeer
property 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
allowPeerToPeer
set totrue
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 notimplement
. TheimplementSibling
method internally calls implement, but it also marks the command as a command that is allowed to be called via a sibling.
Created by Elijah Cobb provided under the MIT license.
Element is a group of developer tools I have built in TypeScript. Check them out at: element-ts.com.
Author: Elijah Cobb
NPM: @element-ts/lithium
Issue Reporting: Github Issues