今回はWebRTCによる 手っ取り早く実装するには 今回使うファイルはこちら 実行画面は以下のようになります 以下、全ソースコードです。 <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>ブラウザP2Pチャット</title> <style> textarea{ background-color: lightgrey; } </style> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> <script src="http://cdn.peerjs.com/0/peer.min.js"></script> <script> // 文字列バイナリ変換(P2P送信文字化け対策) function str2binary(str, callback) { var reader = new FileReader(); reader.onload = function(e){ callback(reader.result); }; reader.readAsArrayBuffer(new Blob([str])); } // バイナリ文字列変換 function binary2str(bin, callback) { var reader = new FileReader(); reader.onload = function(e){ callback(reader.result); }; reader.readAsText(new Blob([bin])); } $(function(){ // 改行コード var LB = "\r\n"; // Peer Server API Keyが必要 var peer = new Peer({key: 'u89af0whga7zaor',debug: false}); // 自分のID取得 peer.on('open', function(id) { $('#myId').text(id); }); // コネクション変数 var conn = null; // 接続 function Open(conn){ conn.on('open', function() { $('#chat').append('接続成功しました' + LB); $('#sendButton').attr('disabled', false); $('#connButton').attr('disabled', true); $('#peerid').attr('readonly', true); $('#peerid').css('background-color', 'lightgrey'); }); } // 切断 function Close(conn){ conn.on('close', function() { $('#chat').append('切断されました' + LB); $('#sendButton').attr('disabled', true); $('#connButton').attr('disabled', false); $('#peerid').attr('readonly', false); $('#peerid').css('background-color', 'white'); $('#peerid').val(''); }); } // 接続エラー function Error(conn){ conn.on('error', function(error) { console.log(error); }); } // 受信 function Recv(conn){ conn.on('data', function(data) { binary2str(data,function(message){ $('#chat').append(message); }); }); } // 接続処理 $('#connButton').click(function(){ var pid = $('#peerid').val(); // 接続先IDを指定して接続 conn = peer.connect(pid); Open(conn); Close(conn); Error(conn); Recv(conn); }); // 接続待ち処理 peer.on('connection', function(connection){ conn = connection; // 接続元id $('#peerid').val(conn.peer); Open(conn); Close(conn); Error(conn); Recv(conn); }); // 送信 $('#sendButton').click(function(){ var message = $('#message').val() + LB; $('#chat').append(message); str2binary(message,function(bin){ conn.send(bin); }); $('#message').val(''); }); }); </script> </head> <body> MyID : <span id="myId"></span><br> 接続先ID : <input type="text" id='peerid'> <input type='button' id='connButton' value='接続'/> <br/> <br/> <input type="text" id="message" value="よろしく!"> <input type="button" id="sendButton" value="送信" disabled="disabled" /><br/> <textarea id="chat" rows="4" cols="40" readonly></textarea> </body> </html> まず、待ち受けのIDを払い出すためにPeerServerにkeyを登録する必要があります var peer = new Peer({key: 'u89af0whga7zaor',debug: false}); 本来PeerServerも作らなければならないようですが 自分でPeerServerを立ち上げる場合は |