LoginSignup
6
4

More than 5 years have passed since last update.

SkyWay WebRTCで多人数テキストチャット部屋を実装してみた

Posted at

SkyWay WebRTCを用いた多人数テキストチャットのサンプルコードです
必要最低限の機能しかありません

処理の流れ

// peerオブジェクトを作成

// roomへの入室処理
   // チャットの送信処理
   // チャットの受信処理

// roomからの退室処理

サンプルコード

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>SkyWay SFURoom テキストチャット</title>
</head>
<body>
    room: <input type="text" id="roomName"> <button id="join">入室</button>
    <br><button id="leave">退室</button>
    <hr>
    <input type="text" id="msg" placeholder="チャットを入力"> <button id="send">send</button>
    <hr>
    <div id="chatLog">

    </div>

    <script type="text/javascript" src="https://cdn.webrtc.ecl.ntt.com/skyway-latest.js"></script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="script.js"></script>
</body>
</body>
</html>
script.js
// peerオブジェクト
const peer = new Peer({
    key: 'API KEY', // 自分のAPIキーを入力
    debug: 3
});

// 入室
let room = null;
$('#join').click(function(){
    room = peer.joinRoom($('#roomName').val(), {mode: 'sfu'});
    chatlog('<i>' + $('#roomName').val() + '</i>に入室しました');

    // チャットを送信
    $('#send').click(function(){
        var msg = $('#msg').val();
        room.send(msg);
        chatlog('自分> ' + msg);
    });

    // チャットを受信
    room.on('data', function(data){
        chatlog('ID: ' + data.src + '> ' + data.data); // data.src = 送信者のpeerid, data.data = 送信されたメッセージ
    });
});

// 退室
$('#leave').click(function(){
    room.close();
    chatlog('<i>' + $('#roomName').val() + '</i>から退室しました');
})


// チャットログに記録するための関数
function chatlog(msg){
    $('#chatLog').append('<p>' + msg + '</p>');
}

参考資料

https://www.slideshare.net/iwashi86/skyway-how-to-use-skyway-webrtc
https://webrtc.ecl.ntt.com/js-reference

コメント

SkyWayもJavaScriptも使い始めたばかりでわからないところだらけです_:(´ཀ`」 ∠):

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4