beaker.peersockets
This API sends and receives messages over Hyperdrive connections
Peersockets enable you to send and receive messages to peers on a hyperdrive.
Technical background
Hyperdrive establishes connections between users to send drive-data. Peersockets piggybacks on those connections by creating additional message-channels.
The peersocket channel is separated into "topics" which are string IDs. You choose to handle messages in a topic by "joining" the topic. If you don't join a topic, your device will still receive the messages, but they'll be discarded.
Note: topics are specific to a hyperdrive. You can only send messages to peers connected to the same hyperdrive.
Every peer has a "peer id" assigned. You send messages to specific peers by using their assigned peer id. You can get the current peers by calling watch()
and handling the "join" and "leave" events.
Peer IDs are created for the network session and will not persist.
Example usage
API
beaker.peersockets.join(topic)
Join a "topic" for sending and receiving messages.
topic String. The topic identifier.
Returns Topic
beaker.peersockets.watch()
Watch for connection events. Emits "join" events for all connections that exist at time-of-call.
Returns PeerEvents
Topic
Instance
Topic
Instance"message" event
Emitted when a peer sends you a message on the topic.
peerId Number. The sending peer's identifier.
message Uint8Array. The message content.
topic.send(peerId, message)
Sends a message to the specified peer.
peerId Number. The target peer's identifier.
message Uint8Array. The message content.
Returns Void.
topic.close()
Closes the topic instance. This will not close the topic globally; other topic instances (e.g. in other tabs) remain active.
Returns Void.
PeerEvents
Instance
PeerEvents
Instance"join" event
Emitted when a new peer connects. When watch()
is called, any existing connections will be emitted as join events.
peerId Number. The connecting peer's identifier.
"leave" event
Emitted when a peer disconnects.
peerId Number. The disconnecting peer's identifier.
peerEvents.close()
Stops listening for messages on the PeerEvents instance. Does not stop connections from being created.
Last updated