Skip to content

Instantly share code, notes, and snippets.

@connor-davis
Created May 25, 2021 13:18
Show Gist options
  • Save connor-davis/8eca2219aa51626e5a824d7a526a3395 to your computer and use it in GitHub Desktop.
Save connor-davis/8eca2219aa51626e5a824d7a526a3395 to your computer and use it in GitHub Desktop.
How I would go about sending offers/answers with hyperswarm
let HyperSwarm = require("hyperswarm");
let sodium = require("sodium-universal");
let ndjson = require("ndjson");
let { RTCPeerConnection, RTCSessionDescription } = require("wrtc");
let swarm = HyperSwarm();
let { crypto_generichash, crypto_generichash_BYTES } = sodium;
let rtcConnection = new RTCPeerConnection();
(() => {
let channelKey = Buffer.alloc(crypto_generichash_BYTES);
crypto_generichash(channelKey, Buffer.from("test-webrtc"));
// let channelKeyString = channelKey.toString("hex");
swarm.join(channelKey, {
announce: true,
lookup: true,
});
swarm.once("connection", (connection, information) => {
let incoming = ndjson.parse();
let outgoing = ndjson.stringify();
connection.pipe(incoming);
outgoing.pipe(connection);
rtcConnection
.createOffer()
.then((offer) =>
rtcConnection.setLocalDescription(new RTCSessionDescription(offer))
)
.then(() =>
outgoing.write({
type: "offerDescription",
offerDescription: rtcConnection.localDescription,
})
);
incoming.on("data", (chunk) => {
let { type } = chunk;
switch (type) {
case "offerDescription":
let { offerDescription } = chunk;
rtcConnection.setRemoteDescription(offerDescription);
rtcConnection
.createAnswer()
.then((answer) =>
rtcConnection.setLocalDescription(
new RTCSessionDescription(answer)
)
)
.then(() => {
outgoing.write({
type: "answerDescription",
answerDescription: rtcConnection.localDescription,
});
console.log(rtcConnection.signalingState);
swarm.leave();
});
break;
case "answerDescription":
let { answerDescription } = chunk;
rtcConnection.setRemoteDescription(answerDescription);
console.log(rtcConnection.signalingState);
swarm.leave();
break;
default:
break;
}
});
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment