File: index.html

package info (click to toggle)
golang-github-centrifugal-centrifuge 0.15.0%2Bgit20210306.f435ba2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,612 kB
  • sloc: javascript: 102; makefile: 2
file content (154 lines) | stat: -rw-r--r-- 7,277 bytes parent folder | download
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            input[type="text"] { width: 300px; }
            .muted {color: #CCCCCC; font-size: 10px;}
        </style>
        <script src="https://unpkg.com/text-encoding@0.6.4/lib/encoding-indexes.js"></script>
        <script src="https://unpkg.com/text-encoding@0.6.4/lib/encoding.js"></script>
        <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/centrifugal/centrifuge-js@master/dist/centrifuge.protobuf.min.js"></script>
        <script type="text/javascript">
            // helper functions to work with escaping html.
            const tagsToReplace = {'&': '&amp;', '<': '&lt;', '>': '&gt;'};
            function replaceTag(tag) {return tagsToReplace[tag] || tag;}
            function safeTagsReplace(str) {return str.replace(/[&<>]/g, replaceTag);}

            const channel = "chat:index";

            window.addEventListener('load', function() {
                const input = document.getElementById("input");
                const container = document.getElementById('messages');

                const centrifuge = new Centrifuge('ws://localhost:8000/connection/websocket?format=protobuf');

                // bind listeners on centrifuge object instance events.
                centrifuge.on('connect', function(ctx){
                    drawText('Connected with client ID ' + ctx.client + ' over ' + ctx.transport);
                    input.removeAttribute('disabled');
                });

                centrifuge.on('publish', function(ctx) {
                    let str = new TextDecoder("utf-8").decode(ctx.data);
                    drawText('Server-side publication from channel ' + ctx.channel + ": " + str);
                });

                centrifuge.on('join', function(ctx) {
                    drawText('Server-side join from channel ' + ctx.channel + ": " + JSON.stringify(ctx.info));
                });

                centrifuge.on('leave', function(ctx) {
                    drawText('Server-side leave from channel ' + ctx.channel + ": " + JSON.stringify(ctx.info));
                });

                centrifuge.on('subscribe', function(ctx) {
                    drawText('Subscribe to server-side channel ' + ctx.channel + ' (resubscribed: ' + ctx.isResubscribe + ', recovered: ' + ctx.recovered + ')');
                });

                centrifuge.on('unsubscribe', function(ctx) {
                    drawText('Unsubscribe from server-side channel ' + ctx.channel);
                });

                centrifuge.on('message', function(data) {
                    const str = new TextDecoder("utf-8").decode(data);
                    drawText(str);
                    // Echo data back to server with 'ack' prefix.
                    const echoData = new TextEncoder("utf-8").encode("ack " + str);
                    centrifuge.send(echoData);
                });

                centrifuge.on('disconnect', function(ctx){
                    drawText('Disconnected: ' + ctx.reason + (ctx.reconnect?", will try to reconnect":", won't try to reconnect"));
                    input.removeAttribute('disabled');
                });

                // subscribe on channel and bind various event listeners. Actual
                // subscription request will be sent after client connects to
                // a server.
                const sub = centrifuge.subscribe(channel, handleMessage)
                        .on("join", handleJoin)
                        .on("leave", handleLeave)
                        .on("unsubscribe", handleUnsubscribe)
                        .on("subscribe", handleSubscribe)
                        .on("error", handleSubscribeError);

                // Trigger actual connection establishing with a server.
                // At this moment actual client work starts - i.e. subscriptions
                // defined start subscribing etc.
                centrifuge.connect();

                function handleSubscribe(ctx) {
                    drawText('Subscribed on channel ' + ctx.channel);

                    const rpcRequest = {"method": "getCurrentYear"}
                    const binary = new TextEncoder("utf-8").encode(JSON.stringify(rpcRequest));

                    centrifuge.rpc(binary).then(function(result){
                        const str = new TextDecoder("utf-8").decode(result.data);
                        drawText("RPC response data: " + str);
                    }, function(err) {
                        drawText("RPC error: " + JSON.stringify(err));
                    });
                }

                function handleSubscribeError(err) {
                    drawText('Error subscribing on channel ' + err.channel + ': ' + err.message);
                }

                function handleMessage(message) {
                    const str = new TextDecoder("utf-8").decode(message.data);
                    const data = JSON.parse(str);
                    let clientID;
                    if (message.info){
                        clientID = message.info.client;
                    } else {
                        clientID = null;
                    }
                    const inputText = data["input"].toString();
                    const text = safeTagsReplace(inputText) + ' <span class="muted">from ' + clientID + '</span>';
                    drawText(text);
                }

                function handleJoin(message) {
                    drawText('Someone joined channel ' + this.channel + ' (uid ' + message.info["client"] + ', user '+ message.info["user"] +')');
                }

                function handleLeave(message) {
                    drawText('Someone left channel ' + this.channel + ' (uid ' + message.info["client"] + ', user '+ message.info["user"] +')');
                }

                function handleUnsubscribe(sub) {
                    drawText('Unsubscribed from channel ' + sub.channel);
                }

                function drawText(text) {
                    let e = document.createElement('li');
                    e.innerHTML = [(new Date()).toString(), ' ' + text].join(':');
                    container.insertBefore(e, container.firstChild);
                }

                document.getElementById('form').addEventListener('submit', function(event) {
                    event.preventDefault();
                    const data = {"input": input.value};
                    const binaryData = new TextEncoder("utf-8").encode(JSON.stringify(data));
                    sub.publish(binaryData).then(function() {
                        console.log('message accepted by server');
                    }, function(err) {
                        drawText("Publish error: " + err.code + ' ' + err.message);
                        console.log('error publishing message', err);
                    });
                    input.value = '';
                });
            });
        </script>
    </head>
    <body>
        <form id="form">
            <input type="text" id="input" autocomplete="off" />
            <input type="submit" id="submit" value="ยป">
        </form>
        <ul id="messages"></ul>
    </body>
</html>