Webrtc-sending-messages
WebRTC-メッセージの送信
それでは、簡単な例を作成しましょう。 まず、「ノードサーバー」を介して「シグナリングサーバー」チュートリアルで作成したシグナリングサーバーを実行します。
ページには3つのテキスト入力があり、1つはログイン用、もう1つはユーザー名用、もう1つは他のピアに送信するメッセージ用です。 _indexl_ファイルを作成し、次のコードを追加します-
<html lang = "en">
<head>
<meta charset = "utf-8"/>
</head>
<body>
<div>
<input type = "text" id = "loginInput"/>
<button id = "loginBtn">Login</button>
</div>
<div>
<input type = "text" id = "otherUsernameInput"/>
<button id = "connectToOtherUsernameBtn">Establish connection</button>
</div>
<div>
<input type = "text" id = "msgInput"/>
<button id = "sendMsgBtn">Send text message</button>
</div>
<script src = "client.js"></script>
</body>
</html>
ログイン、接続の確立、メッセージの送信用の3つのボタンも追加しました。 今_client.js_ファイルを作成し、次のコードを追加します-
var connection = new WebSocket('ws://localhost:9090');
var name = "";
var loginInput = document.querySelector('#loginInput');
var loginBtn = document.querySelector('#loginBtn');
var otherUsernameInput = document.querySelector('#otherUsernameInput');
var connectToOtherUsernameBtn = document.querySelector('#connectToOtherUsernameBtn');
var msgInput = document.querySelector('#msgInput');
var sendMsgBtn = document.querySelector('#sendMsgBtn');
var connectedUser, myConnection, dataChannel;
//when a user clicks the login button
loginBtn.addEventListener("click", function(event) {
name = loginInput.value;
if(name.length > 0) {
send({
type: "login",
name: name
});
}
});
//handle messages from the server
connection.onmessage = function (message) {
console.log("Got message", message.data);
var data = JSON.parse(message.data);
switch(data.type) {
case "login":
onLogin(data.success);
break;
case "offer":
onOffer(data.offer, data.name);
break;
case "answer":
onAnswer(data.answer);
break;
case "candidate":
onCandidate(data.candidate);
break;
default:
break;
}
};
//when a user logs in
function onLogin(success) {
if (success === false) {
alert("oops...try a different username");
} else {
//creating our RTCPeerConnection object
var configuration = {
"iceServers": [{ "url": "stun:stun.1.google.com:19302" }]
};
myConnection = new webkitRTCPeerConnection(configuration, {
optional: [{RtpDataChannels: true}]
});
console.log("RTCPeerConnection object was created");
console.log(myConnection);
//setup ice handling
//when the browser finds an ice candidate we send it to another peer
myConnection.onicecandidate = function (event) {
if (event.candidate) {
send({
type: "candidate",
candidate: event.candidate
});
}
};
openDataChannel();
}
};
connection.onopen = function () {
console.log("Connected");
};
connection.onerror = function (err) {
console.log("Got error", err);
};
//Alias for sending messages in JSON format
function send(message) {
if (connectedUser) {
message.name = connectedUser;
}
connection.send(JSON.stringify(message));
};
シグナリングサーバーへのソケット接続を確立していることがわかります。 ユーザーがログインボタンをクリックすると、アプリケーションはユーザー名をサーバーに送信します。 ログインに成功すると、アプリケーションは_RTCPeerConnection_オブジェクトを作成し、見つかったすべてのicecandidatesを他のピアに送信する_onicecandidate_ハンドラーをセットアップします。 また、dataChannelを作成するopenDataChannel()関数も実行します。 RTCPeerConnectionオブジェクトを作成する場合、ChromeまたはOperaを使用している場合、コンストラクターの2番目の引数(オプション:[\ {RtpDataChannels:true}])は必須です。 次のステップは、他のピアへのオファーを作成することです。 _client.js_ファイルに次のコードを追加します
//setup a peer connection with another user
connectToOtherUsernameBtn.addEventListener("click", function () {
var otherUsername = otherUsernameInput.value;
connectedUser = otherUsername;
if (otherUsername.length > 0) {
//make an offer
myConnection.createOffer(function (offer) {
console.log();
send({
type: "offer",
offer: offer
});
myConnection.setLocalDescription(offer);
}, function (error) {
alert("An error has occurred.");
});
}
});
//when somebody wants to call us
function onOffer(offer, name) {
connectedUser = name;
myConnection.setRemoteDescription(new RTCSessionDescription(offer));
myConnection.createAnswer(function (answer) {
myConnection.setLocalDescription(answer);
send({
type: "answer",
answer: answer
});
}, function (error) {
alert("oops...error");
});
}
//when another user answers to our offer
function onAnswer(answer) {
myConnection.setRemoteDescription(new RTCSessionDescription(answer));
}
//when we got ice candidate from another user
function onCandidate(candidate) {
myConnection.addIceCandidate(new RTCIceCandidate(candidate));
}
ユーザーが[接続の確立]ボタンをクリックすると、アプリケーションが他のピアにSDPオファーを行うことがわかります。 _onAnswer_および_onCandidate_ハンドラーも設定します。 最後に、dataChannelを作成する_openDataChannel()_関数を実装しましょう。 _client.js_ファイルに次のコードを追加します-
//creating data channel
function openDataChannel() {
var dataChannelOptions = {
reliable:true
};
dataChannel = myConnection.createDataChannel("myDataChannel", dataChannelOptions);
dataChannel.onerror = function (error) {
console.log("Error:", error);
};
dataChannel.onmessage = function (event) {
console.log("Got message:", event.data);
};
}
//when a user clicks the send message button
sendMsgBtn.addEventListener("click", function (event) {
console.log("send message");
var val = msgInput.value;
dataChannel.send(val);
});
ここで、接続用のdataChannelを作成し、「メッセージを送信」ボタンのイベントハンドラーを追加します。 このページを2つのタブで開き、2人のユーザーでログインし、接続を確立して、メッセージを送信してみます。 コンソール出力に表示されるはずです。 上記の例はOperaでテストされていることに注意してください。
RTCDataChannelがWebRTC APIの非常に強力な部分であることがわかります。 ピアツーピアゲームやトレントベースのファイル共有など、このオブジェクトには他にも多くのユースケースがあります。