-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclient.js
97 lines (84 loc) · 2.26 KB
/
client.js
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
"use strict";
var NAME = exports.name = "ws-client";
var LOGNAME = "[" + NAME + "]";
var lob = require("lob-enc");
var isNode = typeof window === "undefined";
exports.mesh = function(mesh, cbMesh) {
var WebSocketClient;
if (isNode) {
WebSocketClient = require("ws");
} else {
if (typeof WebSocket === "undefined") {
throw new Error("WebSocket not available");
}
WebSocketClient = WebSocket;
}
var log = mesh.log;
var th = mesh.lib;
var pipes = {};
var tp = {pipes: pipes};
tp.pipe = function(link, path, cbPipe) {
var id = path.url;
if (path.type !== "ws" || id == null) return;
var pipe = pipes[id];
if (pipe) return cbPipe(pipe);
var ws;
try {
ws = new WebSocketClient(id);
} catch (e) {
log.error(LOGNAME, "init error from", id, e.message);
return;
}
// Compatibility shims for browser and node WebSocket
// implementations.
var getmsgbuf, sendmsg;
if (isNode) {
getmsgbuf = function(data) {
return data;
};
sendmsg = function(data, cb) {
ws.send(data, {binary: true}, cb);
};
} else {
ws.binaryType = "arraybuffer";
getmsgbuf = function(data) {
return new Buffer(new Uint8Array(data));
};
sendmsg = function(data, cb) {
ws.send(data);
cb();
};
}
ws.onopen = function() {
log.info(LOGNAME, "connected to", id);
// TODO(Kagami): Keepalive.
pipe = pipes[id] = new th.Pipe(NAME);
pipe.id = id;
pipe.path = path;
ws.onmessage = function(e) {
var packet = lob.decode(getmsgbuf(e.data));
if (!packet) {
var hex = e.data.toString("hex");
log.error(LOGNAME, "dropping invalid packet from", id, hex);
return;
}
mesh.receive(packet, pipe);
};
ws.onclose = function(e) {
delete pipes[id];
ws = null;
log.info(LOGNAME, "disconnected from", id, e);
};
pipe.onSend = function(packet, link, cbSend) {
if (!ws) return; // Disconnected
var buf = lob.encode(packet);
sendmsg(buf, cbSend);
};
cbPipe(pipe);
};
ws.onerror = function(e) {
log.error(LOGNAME, "error from", id, e);
};
};
cbMesh(null, tp);
};