-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathx-server.js
72 lines (57 loc) · 1.84 KB
/
x-server.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
// https://github.com/ttaubert/x-server-js
// (c) 2013 Tim Taubert <[email protected]>
// x-server.js may be freely distributed under the MIT license.
"use strict";
var net = require("net");
var http = require("http");
var WebSocketServer = require("websocket").server;
var server = http.createServer(function (request, response) {
// TODO
});
server.listen(1337, function () {
// TODO
});
var wsServer = new WebSocketServer({
httpServer: server
});
var conn;
var socket;
wsServer.on("request", function (request) {
conn = request.accept(null, request.origin); // TODO
console.log("New WebSocket client");
conn.on("message", function (msg) {
if (msg.type === "binary") {
socket.write(msg.binaryData, undefined, function () {
var id = socket.remoteAddress + ":" + socket.remotePort;
console.log("[%s] Forwarded message from WebSocket to XClient", id);
//console.log(msg.binaryData.toString());
//console.log(msg.binaryData.toJSON());
});
}
});
conn.on("close", function (conn) {
// TODO
});
});
var server = net.createServer(function (sock) {
socket = sock
var id = socket.remoteAddress + ":" + socket.remotePort;
//conn.sendUTF("NEW " + id);
console.log("[%s] XClient accepted", id);
socket.on("data", function (data) {
console.log("[%s] Received data", id);
/*var buffer = new Buffer(data.length + id.length + 1);
buffer.writeUInt8(id.length, 0);
buffer.write(id, 1, null, "ascii");
data.copy(buffer, id.length + 1);*/
console.log("[%s] Forwarding message from XClient to WebSocket", id);
conn.sendBytes(data);
});
socket.on("close", function () {
//conn.sendUTF("END " + id);
console.log("[%s] XClient is gone", id);
});
})
server.listen(6000 + 1, null, null, function () {
console.log("XServer listening on %j", server.address());
});