2018-04-13 03:18:42 +02:00
|
|
|
<!DOCTYPE html>
|
|
|
|
<html>
|
2020-10-31 16:55:23 +01:00
|
|
|
<head>
|
|
|
|
<title>Chat!</title>
|
|
|
|
|
|
|
|
<meta charset="utf-8" />
|
|
|
|
|
|
|
|
<script>
|
|
|
|
'use strict'
|
|
|
|
|
|
|
|
window.onload = () => {
|
|
|
|
let conn = null
|
|
|
|
|
|
|
|
const log = (msg) => {
|
|
|
|
div_log.innerHTML += msg + '<br>'
|
|
|
|
div_log.scroll(0, div_log.scrollTop + 1000)
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|
2020-10-31 16:55:23 +01:00
|
|
|
|
|
|
|
const connect = () => {
|
|
|
|
disconnect()
|
|
|
|
|
|
|
|
const wsUri =
|
|
|
|
(window.location.protocol === 'https:' ? 'wss://' : 'ws://') +
|
|
|
|
window.location.host +
|
|
|
|
'/ws/'
|
|
|
|
|
|
|
|
conn = new WebSocket(wsUri)
|
|
|
|
log('Connecting...')
|
|
|
|
|
|
|
|
conn.onopen = function () {
|
|
|
|
log('Connected.')
|
|
|
|
update_ui()
|
|
|
|
}
|
|
|
|
|
|
|
|
conn.onmessage = function (e) {
|
|
|
|
log('Received: ' + e.data)
|
|
|
|
}
|
|
|
|
|
|
|
|
conn.onclose = function () {
|
|
|
|
log('Disconnected.')
|
|
|
|
conn = null
|
|
|
|
|
|
|
|
update_ui()
|
|
|
|
}
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|
2020-10-31 16:55:23 +01:00
|
|
|
|
|
|
|
const disconnect = () => {
|
|
|
|
if (conn) {
|
|
|
|
log('Disconnecting...')
|
|
|
|
conn.close()
|
|
|
|
conn = null
|
|
|
|
|
|
|
|
update_ui()
|
|
|
|
}
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|
2020-10-31 16:55:23 +01:00
|
|
|
|
|
|
|
const update_ui = () => {
|
|
|
|
if (!conn) {
|
|
|
|
span_status.textContent = 'disconnected'
|
|
|
|
btn_connect.textContent = 'Connect'
|
|
|
|
} else {
|
|
|
|
span_status.textContent = `connected (${conn.protocol})`
|
|
|
|
btn_connect.textContent = 'Disconnect'
|
|
|
|
}
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|
2020-10-31 16:55:23 +01:00
|
|
|
|
|
|
|
btn_connect.onclick = () => {
|
|
|
|
if (!conn) {
|
|
|
|
connect()
|
|
|
|
} else {
|
|
|
|
disconnect()
|
|
|
|
}
|
|
|
|
|
|
|
|
update_ui()
|
|
|
|
}
|
|
|
|
|
|
|
|
btn_send.onclick = () => {
|
|
|
|
if (!conn) return
|
|
|
|
|
|
|
|
const text = input_text.value
|
|
|
|
log('Sending: ' + text)
|
|
|
|
conn.send(text)
|
|
|
|
|
|
|
|
input_text.value = ''
|
|
|
|
input_text.focus()
|
|
|
|
}
|
|
|
|
|
|
|
|
input_text.onkeyup = (e) => {
|
|
|
|
if (e.key === 'Enter') {
|
|
|
|
btn_send.click()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
</script>
|
|
|
|
</head>
|
|
|
|
|
|
|
|
<body>
|
|
|
|
<h3>Chat!</h3>
|
|
|
|
<div>
|
|
|
|
<button id="btn_connect">Connect</button>
|
|
|
|
Status: <span id="span_status">disconnected</span>
|
|
|
|
</div>
|
|
|
|
|
|
|
|
<div
|
|
|
|
id="div_log"
|
|
|
|
style="width: 20em; height: 15em; overflow: auto; border: 1px solid black"
|
|
|
|
></div>
|
|
|
|
|
|
|
|
<input id="input_text" type="text" />
|
|
|
|
<input id="btn_send" type="button" value="Send" />
|
|
|
|
</body>
|
2018-04-13 03:18:42 +02:00
|
|
|
</html>
|