Debian Codegraph @

_examples/custom_ws_nhooyr/index.html

raw
1 <!DOCTYPE html>
2 <html>
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
26 centrifuge.setConnectData({"user-agent": navigator.userAgent});
27
28 // bind listeners on centrifuge object instance events.
29 centrifuge.on('connect', function(ctx){
30 drawText('Connected with client ID ' + ctx.client + ' over ' + ctx.transport + ' with data: ' + JSON.stringify(ctx.data));
31 input.removeAttribute('disabled');
32 });
33
34 centrifuge.on('message', function(data) {
35 drawText('Message: ' + JSON.stringify(data));
36 // Echo data back to server.
37 centrifuge.send(data);
38 });
39
40 centrifuge.on('publish', function(ctx) {
41 drawText('Server-side publication from channel ' + ctx.channel + ": " + JSON.stringify(ctx.data));
42 });
43
44 centrifuge.on('join', function(ctx) {
45 drawText('Server-side join from channel ' + ctx.channel + ": " + JSON.stringify(ctx.info));
46 });
47
48 centrifuge.on('leave', function(ctx) {
49 drawText('Server-side leave from channel ' + ctx.channel + ": " + JSON.stringify(ctx.info));
50 });
51
52 centrifuge.on('subscribe', function(ctx) {
53 drawText('Subscribe to server-side channel ' + ctx.channel);
54 });
55
56 centrifuge.on('unsubscribe', function(ctx) {
57 drawText('Unsubscribe from server-side channel ' + ctx.channel);
58 });
59
60 centrifuge.on('disconnect', function(ctx){
61 drawText('Disconnected: ' + ctx.reason + (ctx.reconnect?", will try to reconnect":", won't try to reconnect"));
62 input.setAttribute('disabled', 'true');
63 });
64
65 // show how many users currently in channel.
66 function showPresence(sub) {
67 sub.presence().then(function(result) {
68 let count = 0;
69 for (let key in result.presence){
70 count++;
71 }
72 drawText('Presence: now in this room – ' + count + ' clients');
73 }, function(err) {
74 drawText("Presence error: " + JSON.stringify(err));
75 });
76 }
77
78 // subscribe on channel and bind various event listeners. Actual
79 // subscription request will be sent after client connects to
80 // a server.
81 const sub = centrifuge.subscribe(channel, handleMessage)
82 .on("join", handleJoin)
83 .on("leave", handleLeave)
84 .on("unsubscribe", handleUnsubscribe)
85 .on("subscribe", handleSubscribe)
86 .on("error", handleSubscribeError);
87
88 showPresence(sub);
89
90 // Trigger actual connection establishing with a server.
91 // At this moment actual client work starts - i.e. subscriptions
92 // defined start subscribing etc.
93 centrifuge.connect();
94
95 function handleSubscribe(ctx) {
96 drawText('Subscribed on channel ' + ctx.channel + ' (resubscribed: ' + ctx.isResubscribe + ', recovered: ' + ctx.recovered + ')');
97 if (ctx.isResubscribe) {
98 showPresence(sub);
99 }
100
101 // This can be whatever JSON you want.
102 const rpcRequest = {"method": "getCurrentYear"}
103
104 centrifuge.rpc(rpcRequest).then(function(data){
105 drawText("RPC response data: " + JSON.stringify(data));
106 }, function(err) {
107 drawText("RPC error: " + JSON.stringify(err));
108 });
109 }
110
111 function handleSubscribeError(err) {
112 drawText('Error subscribing on channel ' + err.channel + ': ' + err.message);
113 }
114
115 function handleMessage(message) {
116 let clientID;
117 if (message.info){
118 clientID = message.info.client;
119 } else {
120 clientID = null;
121 }
122 const inputText = message.data["input"].toString();
123 const text = safeTagsReplace(inputText) + ' <span class="muted">from ' + clientID + '</span>';
124 drawText(text);
125 }
126
127 function handleJoin(message) {
128 drawText('Client joined channel ' + this.channel + ' (uid ' + message.info["client"] + ', user '+ message.info["user"] +')');
129 }
130
131 function handleLeave(message) {
132 drawText('Client left channel ' + this.channel + ' (uid ' + message.info["client"] + ', user '+ message.info["user"] +')');
133 }
134
135 function handleUnsubscribe(sub) {
136 drawText('Unsubscribed from channel ' + sub.channel);
137 }
138
139 function drawText(text) {
140 let e = document.createElement('li');
141 e.innerHTML = [(new Date()).toString(), ' ' + text].join(':');
142 container.insertBefore(e, container.firstChild);
143 }
144
145 document.getElementById('form').addEventListener('submit', function(event) {
146 event.preventDefault();
147 sub.publish({"input": input.value}).then(function() {
148 // console.log('message accepted by server');
149 }, function(err) {
150 // console.log('error publishing message', err);
151 });
152 input.value = '';
153 });
154 });
155 </script>
156 </head>
157 <body>
158 <form id="form">
159 <input type="text" id="input" autocomplete="off" />
160 <input type="submit" id="submit" value="»">
161 </form>
162 <ul id="messages"></ul>
163 </body>
164 </html>