-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathws.js
56 lines (46 loc) · 1.78 KB
/
ws.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
// websockets
// (c)copyright 2018 by Gerald Wodni <[email protected]>
"use strict";
const url = require( "url" );
const WebSocket = require( "ws" );
const qs = require( "qs" );
module.exports = function _ws( k ) {
var handlers = {}
function getTarget( req ) {
/* host */
var fullUrl = url.parse( "http://" + req.headers.host + req.url );
let hostname = fullUrl.hostname;
if( process.env.KERN_STATIC_HOST )
hostname = process.env.KERN_STATIC_HOST;
let website = k.hierarchy.website( hostname ) || "default";
req.kern = {
website: website,
pathname: fullUrl.pathname
}
req.params = qs.parse( fullUrl.query );
}
const wss = new WebSocket.Server({
server: k.server,
/* 404 if handler is not set */
verifyClient: function _wsVerifyClient( info, cb ) {
getTarget( info.req );
/* handler exist? */
let handlerUrl = info.req.kern.website + info.req.kern.pathname;
if( handlers.hasOwnProperty( handlerUrl ) )
cb( true, "", "" );
else {
console.log( "Unknown WebSocket Reqest:".bold.red, info.req.kern.website, info.req.kern.pathname );
cb( false, 404, "No Handler" );
}
}
});
wss.on("connection", function _wsConnection( ws, req ) {
console.log( "WebSocket Connection:".bold.yellow, req.kern.website, req.kern.pathname );
let handlerUrl = req.kern.website + req.kern.pathname;
handlers[ handlerUrl ]( ws, req );
});
return function _wsRegister( website, path, callback ) {
console.log( "WebSocket Register".bold.yellow, path );
handlers[ website + path ] = callback;
};
};