summaryrefslogtreecommitdiff
path: root/webcards/scripts/client/sock.js
blob: 78c41956f6b97ddeffc3a01fa0d221f074c666fe (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
function SockWorker(serveraddr, version, callback) {
    this.server = serveraddr;
    this.version = version;
    this.cb = callback;
}

SockWorker.prototype = {
    init: function() {
        if(this.server == "" || this.server == null) {
            return;
        }
        try {
            this.socket = new WebSocket(this.server);

            this.socket.addEventListener("open", this.o.bind(this));
            this.socket.addEventListener("message", this.msg.bind(this));

            this.socket.addEventListener("closed", this.c.bind(this));
            this.socket.addEventListener("error", this.err.bind(this));
        } catch (e) {
            this.err();
        }
    },

    o: function() {
        this.send("version", this.version);
    },

    msg: function(e) {
        if(typeof e.data == "string") {
            var dat = JSON.parse(e.data)
            this.cb(dat);
        }
    },

    c: function() {
        this.cb({type: "close", data: ""});
    },

    err: function() {
        this.cb({type: "error", data: ""});
    },

    close: function() {
        this.socket.close();
    },

    send: function(type, data) {
        var m = new Message(type, data);
        this.socket.send(m.stringify())
    }
};