WebSocket2019年8月31日 | |
はじめにWebSocket は、ブラウザとサーバーの間で双方向通信を行うものである。 WebSocket の例エコーサーバーが公開されているので、それに対してメッセージを送って返信を受け取るコードを書くと、次のようになる。(2023.5.28 追記: エコーサーバーの公開は停止されている)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebScoket テスト</title>
</head>
<body>
<label for="messageInput">Message: </label><input type="text" id="messageInput">
<input type="submit" value="Send" id="sendSubmit">
<p id="output"></p>
<script>
const uri = "wss://echo.websocket.org/";
const sendSubmit = document.getElementById("sendSubmit");
const messageInput = document.getElementById("messageInput");
const output = document.getElementById("output");
function write(msg) {
output.innerHTML += msg + "<br>";
}
function sendMessage() {
const ws = new WebSocket(uri);
ws.onopen = function(e) {
write("Connected");
const msg = messageInput.value
write("Send: " + msg);
ws.send(msg);
};
ws.onmessage = function(e) {
write("Response: " + e.data);
ws.close();
};
ws.onclose = function(e) {
write("Disconnected");
};
ws.onerror = function(e) {
write("Error: " + e.data);
};
}
sendSubmit.addEventListener("click", sendMessage);
</script>
</body>
</html>
参考 | |
| PENGUINITIS | |