-
Notifications
You must be signed in to change notification settings - Fork 16
/
app.js
74 lines (62 loc) · 2.12 KB
/
app.js
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
const neffos = require('neffos.js');
var scheme = document.location.protocol == "https:" ? "wss" : "ws";
var port = document.location.port ? ":" + document.location.port : "";
var wsURL = scheme + "://" + document.location.hostname + port + "/echo";
var outputTxt = document.getElementById("output");
function addMessage(msg) {
outputTxt.innerHTML += msg + "\n";
}
function handleError(reason) {
console.log(reason);
window.alert(reason);
}
function handleNamespaceConnectedConn(nsConn) {
const inputTxt = document.getElementById("input");
const sendBtn = document.getElementById("sendBtn");
sendBtn.disabled = false;
sendBtn.onclick = function () {
const input = inputTxt.value;
inputTxt.value = "";
nsConn.emit("chat", input);
addMessage("Me: " + input);
};
}
async function runExample() {
try {
const conn = await neffos.dial(wsURL, {
default: { // "default" namespace.
_OnNamespaceConnected: function (nsConn, msg) {
addMessage("connected to namespace: " + msg.Namespace);
handleNamespaceConnectedConn(nsConn);
},
_OnNamespaceDisconnect: function (nsConn, msg) {
addMessage("disconnected from namespace: " + msg.Namespace);
},
_OnAnyEvent: function (nsConn, msg) { // any event.
if (!neffos.isSystemEvent(msg.Event)) {
console.log(msg);
}
},
chat: function (nsConn, msg) { // "chat" event.
addMessage(msg.Body);
}
}
}, {
// if > 0 then on network failures it tries to reconnect every 5 seconds, defaults to 0 (disabled).
reconnect: 5000,
// custom headers:
headers: {
// 'X-Username': 'kataras',
}
});
// You can either wait to conenct or just conn.connect("connect")
// and put the `handleNamespaceConnectedConn` inside `_OnNamespaceConnected` callback instead.
// const nsConn = await conn.connect("default");
// handleNamespaceConnectedConn(nsConn);
conn.connect("default");
} catch (err) {
console.log("try-catch on await neffos.dial.");
handleError(err);
}
}
runExample();