Skip to content

Instantly share code, notes, and snippets.

@linquize
Created November 5, 2018 16:26
Show Gist options
  • Save linquize/dbfe6f09b2cff2b8e7bedf955cf07a26 to your computer and use it in GitHub Desktop.
Save linquize/dbfe6f09b2cff2b8e7bedf955cf07a26 to your computer and use it in GitHub Desktop.
Caddy Websocket test
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Caddy Websocket test</title>
</head>
<body>
<pre>
<span id="console" style="border: 1px solid black"></span>
</pre>
<script>
function replaceCrCr(str) {
for (let i = str.indexOf('\r\n'); i >= 0; i = str.indexOf('\r\n'))
str = str.substr(0, i) + str.substr(i + 1);
let firstIndex = str.indexOf('\r');
let lastIndex = str.lastIndexOf('\r');
if (firstIndex < 0)
return str;
if (firstIndex !== lastIndex)
return str.substr(0, firstIndex) + str.substr(lastIndex + 1);
let nIndex = str.lastIndexOf('\n');
if (nIndex >= 0)
return str.substr(0, nIndex + 1) + str.substr(lastIndex + 1);
return str;
}
function wsOnMessage(e) {
let cs = document.getElementById('console');
let data = replaceCrCr(e.data);
let rIndex = data.indexOf('\r')
if (rIndex >= 0) {
let oldText = cs.innerText;
let nIndex = oldText.lastIndexOf('\n');
if (nIndex >= 0)
cs.innerText = oldText.substr(0, nIndex + 1) + data.substr(rIndex + 1);
else
cs.innerText = data.substr(rIndex + 1);
} else
cs.innerText += data;
}
let ws = new WebSocket("ws://localhost:2015/test");
ws.onopen = () => document.getElementById('console').innerText += '[WS OPEN]' + '\n';
ws.onmessage = wsOnMessage;
ws.onclose = () => document.getElementById('console').innerText += '[WS CLOSED]' + '\n';
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment