Skip to content

Instantly share code, notes, and snippets.

@legokichi
Forked from voluntas/webrtc_quic.js
Created February 2, 2019 09:20
Show Gist options
  • Select an option

  • Save legokichi/c589eba46cb9df7fbdb696205e3f9076 to your computer and use it in GitHub Desktop.

Select an option

Save legokichi/c589eba46cb9df7fbdb696205e3f9076 to your computer and use it in GitHub Desktop.
RTCQuicTransport の動作サンプル
// Chrome Canary M74
// chrome://flags で Experimental Web Platform features を有効にすれば使えるようになる
// https://developers.google.com/web/updates/2019/01/rtcquictransport-api
// https://github.com/shampson/RTCQuicTransport-Origin-Trial-Documentation
const iceTransport1 = new RTCIceTransport;
const iceTransport2 = new RTCIceTransport;
const quicTransport1 = new RTCQuicTransport(iceTransport1);
const quicTransport2 = new RTCQuicTransport(iceTransport2);
// IP アドレス候補をかき集める
iceTransport1.gather({});
iceTransport2.gather({});
iceTransport1.onicecandidate = e => {
if (e.candidate) {
iceTransport2.addRemoteCandidate(e.candidate);
}
}
iceTransport2.onicecandidate = e => {
if (e.candidate) {
iceTransport1.addRemoteCandidate(e.candidate);
}
}
// サーバを listen する
iceTransport2.start(iceTransport1.getLocalParameters());
// クライアントの鍵 (PSK) を渡す
quicTransport2.listen(quicTransport1.getKey());
// クライアントからサーバに connect する
iceTransport1.start(iceTransport2.getLocalParameters());
quicTransport1.connect();
let readStream;
quicTransport2.onquicstream = e => {
// ストリームが上がってくる
readStream = e.stream;
}
// connect まで少し時間かかるなので、少し待つ
// ストリーム作成
const quicStream = quicTransport1.createStream();
// データを送る、遅れるのはバイナリデータのみ
quicStream.write({data: new Uint8Array([1,2,3])});
quicStream.write({data: new Uint8Array([4,5,6])});
// データ終了、ストリームが終了するのではなく一つのデータが終了するだけ
quicStream.write({finish: true});
// 読み込み
await readStream.waitForReadable(readStream.readBufferedAmount);
const readBuffer = new Uint8Array(readStream.readBufferedAmount);
const { amount, finished } = readStream.readInto(readBuffer);
console.log(readBuffer);
// ストリーム終了、クライアント側から終了できる
readStream.reset();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment