summaryrefslogtreecommitdiff
path: root/examples/websocket-client.js
blob: d258f52e4c4ac9258ff360cc2d8c07c0ab6d990e (plain)
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
// SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
// SPDX-FileCopyrightText: 2019 Sonny Piers <sonny@fastmail.net>

// This is an example of a WebSocket client in Gjs using libsoup
// https://developer.gnome.org/libsoup/stable/libsoup-2.4-WebSockets.html

import Soup from 'gi://Soup?version=3.0';
import GLib from 'gi://GLib';

const loop = GLib.MainLoop.new(null, false);

const session = new Soup.Session();
const message = new Soup.Message({
    method: 'GET',
    uri: GLib.Uri.parse('wss://ws.postman-echo.com/raw', GLib.UriFlags.NONE),
});
const decoder = new TextDecoder();

session.websocket_connect_async(message, null, [], null, null, websocket_connect_async_callback);

function websocket_connect_async_callback(_session, res) {
    let connection;

    try {
        connection = session.websocket_connect_finish(res);
    } catch (err) {
        logError(err);
        loop.quit();
        return;
    }

    connection.connect('closed', () => {
        log('closed');
        loop.quit();
    });

    connection.connect('error', (self, err) => {
        logError(err);
        loop.quit();
    });

    connection.connect('message', (self, type, data) => {
        if (type !== Soup.WebsocketDataType.TEXT)
            return;

        const str = decoder.decode(data.toArray());
        log(`message: ${str}`);
        connection.close(Soup.WebsocketCloseCode.NORMAL, null);
    });

    log('open');
    connection.send_text('hello');
}

loop.run();