Skip to content

Instantly share code, notes, and snippets.

@voluntas
Last active September 17, 2022 22:46
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save voluntas/9ef8cae27b238aa030c41d58190eb71a to your computer and use it in GitHub Desktop.
Save voluntas/9ef8cae27b238aa030c41d58190eb71a to your computer and use it in GitHub Desktop.
RTCQuicTransport の動作サンプル
// Chrome Canary M74
// chrome://flags で Experimental Web Platform features を有効にすれば使えるようになる
// mDNS を有効にしていると上手く動かないかもしれないので要注意
// 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 アドレス候補をかき集める
// iceServers はおそらく、効いていない
iceTransport1.gather({iceServers: [{urls: ['stun:stun.l.google.com:19302']}]});
iceTransport2.gather({iceServers: [{urls: ['stun:stun.l.google.com:19302']}]});
iceTransport1.onicecandidate = e => {
if (e.candidate) {
console.log(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