Debian Codegraph @

_examples/chat_json/index.html

raw
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title></title>
6 <style type="text/css">
7 input[type="text"] { width: 300px; }
8 .muted {color: #CCCCCC; font-size: 10px;}
9 </style>
10 <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
11 <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/centrifugal/centrifuge-js@master/dist/centrifuge.min.js"></script>
12 <script type="text/javascript">
13 // helper functions to work with escaping html.
14 const tagsToReplace = {'&': '&amp;', '<': '&lt;', '>': '&gt;'};
15 function replaceTag(tag) {return tagsToReplace[tag] || tag;}
16 function safeTagsReplace(str) {return str.replace(/[&<>]/g, replaceTag);}
17
18 const channel = "chat:index";
19
20 window.addEventListener('load', function() {
21 const input = document.getElementById("input");
22 const container = document.getElementById('messages');
23
24 const centrifuge = new Centrifuge('ws://localhost:8000/connection/websocket');
25 // const centrifuge = new Centrifuge('http://localhost:8000/connection/sockjs', {
26 // sockjsTransports: [
27 // "xhr-streaming",
28 // ]
29 // });
30
31 centrifuge.setConnectData({"user-agent": navigator.userAgent});
32
33 // bind listeners on centrifuge object instance events.
34 centrifuge.on('connect', function(ctx){
35 drawText('Connected with client ID ' + ctx.client + ' over ' + ctx.transport + ' with data: ' + JSON.stringify(ctx.data));
36 input.removeAttribute('disabled');
37 });
38
39 centrifuge.on('message', function(data) {
40 drawText('Message: ' + JSON.stringify(data));
41 // Echo data back to server.
42 centrifuge.send(data);
43 });
44
45 centrifuge.on('publish', function(ctx) {
46 drawText('Server-side publication from channel ' + ctx.channel + ": " + JSON.stringify(ctx.data));
47 });
48
49 centrifuge.on('join', function(ctx) {
50 drawText('Server-side join from channel ' + ctx.channel + ": " + JSON.stringify(ctx.info));
51 });
52
53 centrifuge.on('leave', function(ctx) {
54 drawText('Server-side leave from channel ' + ctx.channel + ": " + JSON.stringify(ctx.info));
55 });
56
57 centrifuge.on('subscribe', function(ctx) {
58 drawText('Subscribe to server-side channel ' + ctx.channel + ' (resubscribed: ' + ctx.isResubscribe + ', recovered: ' + ctx.recovered + ')');
59 });
60
61 centrifuge.on('unsubscribe', function(ctx) {
62 drawText('Unsubscribe from server-side channel ' + ctx.channel);
63 });
64
65 centrifuge.on('disconnect', function(ctx){
66 drawText('Disconnected: ' + ctx.reason + (ctx.reconnect?", will try to reconnect":", won't try to reconnect"));
67 input.setAttribute('disabled', 'true');
68 });
69
70 // show how many users currently in channel.
71 function showPresence(sub) {
72 sub.presence().then(function(result) {
73 let count = 0;
74 for (let key in result.presence){
75 count++;
76 }
77 drawText('Presence: now in this room – ' + count + ' clients');
78 }, function(err) {
79 drawText("Presence error: " + JSON.stringify(err));
80 });
81 }
82
83 // subscribe on channel and bind various event listeners. Actual
84 // subscription request will be sent after client connects to
85 // a server.
86 const sub = centrifuge.subscribe(channel, handleMessage)
87 .on("join", handleJoin)
88 .on("leave", handleLeave)
89 .on("unsubscribe", handleUnsubscribe)
90 .on("subscribe", handleSubscribe)
91 .on("error", handleSubscribeError);
92
93 showPresence(sub);
94
95 // Trigger actual connection establishing with a server.
96 // At this moment actual client work starts - i.e. subscriptions
97 // defined start subscribing etc.
98 centrifuge.connect();
99
100 function handleSubscribe(ctx) {
101 drawText('Subscribed on channel ' + ctx.channel + ' (resubscribed: ' + ctx.isResubscribe + ', recovered: ' + ctx.recovered + ')');
102 if (ctx.isResubscribe) {
103 showPresence(sub);
104 }
105
106 // This can be whatever JSON you want.
107 const rpcRequest = {"method": "getCurrentYear"};
108
109 centrifuge.rpc(rpcRequest).then(function(data){
110 drawText("RPC response data: " + JSON.stringify(data));
111 }, function(err) {
112 drawText("RPC error: " + JSON.stringify(err));
113 });
114 }
115
116 function handleSubscribeError(err) {
117 drawText('Error subscribing on channel ' + err.channel + ': ' + err.message);
118 }
119
120 function handleMessage(message) {
121 let clientID;
122 if (message.info){
123 clientID = message.info.client;
124 } else {
125 clientID = null;
126 }
127 const inputText = message.data["input"].toString();
128 const text = safeTagsReplace(inputText) + ' <span class="muted">from ' + clientID + '</span>';
129 drawText(text);
130 }
131
132 function handleJoin(message) {
133 drawText('Client joined channel ' + this.channel + ' (uid ' + message.info["client"] + ', user '+ message.info["user"] +')');
134 }
135
136 function handleLeave(message) {
137 drawText('Client left channel ' + this.channel + ' (uid ' + message.info["client"] + ', user '+ message.info["user"] +')');
138 }
139
140 function handleUnsubscribe(sub) {
141 drawText('Unsubscribed from channel ' + sub.channel);
142 }
143
144 function drawText(text) {
145 let e = document.createElement('li');
146 e.innerHTML = [(new Date()).toString(), ' ' + text].join(':');
147 container.insertBefore(e, container.firstChild);
148 }
149
150 document.getElementById('form').addEventListener('submit', function(event) {
151 event.preventDefault();
152 sub.publish({"input": input.value}).then(function() {
153 drawText("Successfully published to channel");
154 }, function(err) {
155 drawText("Publish error: " + JSON.stringify(err));
156 });
157 input.value = '';
158 });
159 });
160 </script>
161 </head>
162 <body>
163 <form id="form">
164 <label for="input"></label><input type="text" id="input" autocomplete="off" />
165 <input type="submit" id="submit" value="»">
166 </form>
167 <ul id="messages"></ul>
168 </body>
169 </html>