-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
81 lines (67 loc) · 2.61 KB
/
index.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
81
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!--In case we want to define CSS attributes in another file
<link rel="stylesheet" type="text/css" href="path/to/your/stylesheet.css">
-->
</head>
<body>
<h1>Real time Messaging</h1>
<pre id="messages" style="height: 400px; overflow: scroll"></pre>
<input type="text" id="messageBox" placeholder="Type your message here" style="display: block; width: 100%;
margin-bottom: 10px; padding:10px;" />
<button id="send" title="Send Message!" style="width:100%; height: 30px;">Send Message</button>
</body>
<script>
(function () {
const sendBtn = document.querySelector('#send');
const messages = document.querySelector('#messages');
const messageBox = document.querySelector('#messageBox')
let ws;
function showMessage(message) {
messages.textContent += `\n\n${message}`;
messages.scrollTop = messages.scrollHeight; // set the scrollTop property to the bottom of the pre tag's content(then next content will be displayed at the bottom of previous content)
messageBox.value = '';
}
function init() {
if (ws) {
ws.onerror = ws.onopen = ws.onclose = null;
ws.close();
}
ws = new WebSocket('ws://localhost:3000');
ws.onopen = () => {
console.log('Connection opened!');
}
//We can also write like this: (and also do the same for other works on ws)
// ws.addEventListener('open', function (event) {
// console.log('Connected to WS Server')
// });
ws.onmessage = (event) => {
var data = new Blob([event.data], { type: 'text/plain' });
var reader = new FileReader();
reader.onload = function () {
//console.log('Message from server: ', reader.result);
showMessage(reader.result);
};
reader.readAsText(data);
}
ws.onclose = function () {
ws = null;
}
}
sendBtn.onclick = function () {
if (!ws) {
showMessage("No WebSocket connection :(");
return;
}
ws.send(messageBox.value); //send to server
showMessage(messageBox.value);
}
init();
})();
</script>
</html>