-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefault.js
More file actions
81 lines (69 loc) · 1.89 KB
/
default.js
File metadata and controls
81 lines (69 loc) · 1.89 KB
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
var wsUri = 'ws://echo.websocket.org/';
var webSocket;
var timerId = 0;
$(function () {
if (checkSupported()) {
connect();
$('#btnSend').click(doSend());
}
});
function writeOutput(message) {
var $output = $('#divOutput');
$output.html(`${$output.html()}<br />${message}`);
}
function checkSupported() {
if (window.WebSocket) {
writeOutput('WebSockets supported!');
return true;
}
else {
writeOutput('WebSockets not supported!');
$('#btnSend').attr('disabled', 'disabled');
return false;
}
}
function connect() {
webSocket = new WebSocket(wsUri);
webSocket.onopen = function (event) { onOpen(event) };
webSocket.onclose = function (event) { onClose(event) };
webSocket.onmessage = function (event) { onMessage(event) };
webSocket.onerror = function (event) { onError(event) };
}
function onOpen(evt) {
keepAlive();
writeOutput("CONNECTED");
}
function onClose(evt) {
cancelKeepAlive();
writeOutput("DISCONNECTED");
}
function onMessage(evt) {
writeOutput('RESPONSE: ' + evt.data);
}
function onError(evt) {
writeOutput('ERROR: ' + evt.data);
}
function doSend() {
// CONNECTING = 0 Connection is not yet open.
// OPEN = 1 Connection is open and ready to communicate.
// CLOSING = 2 Connection is in the process of closing.
// CLOSED = 3 Connection is closed or couldn’t be opened.
if (webSocket.readyState != webSocket.OPEN) {
writeOutput("NOT OPEN: " + $('#txtMessage').val());
return;
}
writeOutput("SENT: " + $('#txtMessage').val());
webSocket.send($('#txtMessage').val())
}
function keepAlive() {
var timeout = 15000;
if (webSocket.readyState == webSocket.OPEN) {
webSocket.send('');
}
timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
if (timerId) {
cancelTimeout(timerId);
}
}