Kill the WebSocketServer
function _cmdClose() {
if (_wsServer) {
_wsServer.close();
_wsServer = null;
}
}
Initializes the socket server.
function _cmdStart(port) {
_createServer(port);
}
function _createServer(socketPort) {
if (!_wsServer) {
// TODO: make port configurable, or use random port
_wsServer = new WebSocketServer({port: socketPort});
_wsServer.on("connection", function (ws) {
ws.on("message", function (msg) {
console.log("WebSocketServer - received - " + msg);
var msgObj;
try {
msgObj = JSON.parse(msg);
} catch (e) {
console.error("webSocketTransport: Error parsing message: " + msg);
return;
}
if (msgObj.type === "message") {
_domainManager.emitEvent("webSocketTransport", "message", msgObj.message);
} else {
console.error("webSocketTransport: Got bad socket message type: " + msg);
}
}).on("error", function (e) {
console.error("webSocketTransport: Error on socket : " + e);
}).on("close", function () {
console.log("webSocketTransport closed");
});
}).on("error", function (e) {
console.error("webSocketTransport: Error on live preview server creation: " + e);
});
}
}
Initializes the domain and registers commands.
function init(domainManager) {
_domainManager = domainManager;
if (!domainManager.hasDomain("webSocketTransport")) {
domainManager.registerDomain("webSocketTransport", {major: 0, minor: 1});
}
domainManager.registerEvent(
"webSocketTransport",
"message",
[
{
name: "msg",
type: "string",
description: "JSON message from client page"
}
]
);
domainManager.registerCommand(
"webSocketTransport", // domain name
"start", // command name
_cmdStart, // command handler function
false, // this command is synchronous in Node
"Creates the WS server",
[
{
name: "port",
type: "number",
description: "Port on which server needs to listen"
}
],
[]
);
domainManager.registerCommand(
"webSocketTransport", // domain name
"close", // command name
_cmdClose, // command handler function
false, // this command is synchronous in Node
"Kills the websocket server",
[]
);
}
exports.init = init;