forked from OpenAyame/ayame-web-sdk-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatachannel.html
80 lines (79 loc) · 2.94 KB
/
datachannel.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Ayame DataChannel Sample</title>
<link rel="stylesheet" href="https://cdn.rawgit.com/Chalarangelo/mini.css/v3.0.1/dist/mini-default.min.css">
</head>
<body>
<header class="sticky row">
<h4>Ayame DataChannel Sample</h4>
</header>
<div>
<p>ルームID
<input id="roomIdInput" type="text" value=""></input>
</p>
<p>クライアントID
<input id="clientIdInput" disabled type="text" value=""></input>
</p>
<button onclick="startConn();">接続</button>
<button onclick="disconnect();">切断</button>
<p> 送信するメッセージ
<input id="sendDataInput" type="text" value="🐶"></input>
</p>
<button onclick="sendData();">送信</button>
<p> 受信したメッセージ </p>
<textarea style="height:200px;" id="messages" disabled type="text" value=""></textarea>
</div>
<script src="https://cdn.jsdelivr.net/npm/@open-ayame/[email protected]/dist/ayame.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.7.0/qs.min.js"></script>
<script src="./main.js"></script>
<script type="text/javascript">
const options = Ayame.defaultOptions;
options.clientId = clientId ? clientId : options.clientId;
if (signalingKey) {
options.signalingKey = signalingKey;
}
let conn;
const disconnect = () => {
if (conn) {
conn.disconnect();
}
}
let dataChannel = null;
const label = 'dataChannel';
const startConn = async () => {
conn = Ayame.connection(signalingUrl, roomId, options, true);
conn.on('open', async (e) => {
dataChannel = await conn.createDataChannel(label);
if (dataChannel) {
dataChannel.onmessage = onMessage;
}
});
conn.on('datachannel', (channel) => {
if (!dataChannel) {
dataChannel = channel;
dataChannel.onmessage = onMessage;
}
});
conn.on('disconnect', (e) => {
console.log(e);
dataChannel = null;
});
await conn.connect(null);
};
const sendData = () => {
const data = document.querySelector("#sendDataInput").value;
if (dataChannel && dataChannel.readyState === 'open') {
dataChannel.send(data);
}
};
document.querySelector("#roomIdInput").value = roomId;
document.querySelector("#clientIdInput").value = options.clientId;
function onMessage(e) {
const messages = document.querySelector("#messages").value;
newMessages = messages ? (messages + '\n' + e.data) : e.data;
document.querySelector("#messages").value = newMessages;
}
</script>
</body>
</html>