Open Model Railroad Network (OpenMRN)
Loading...
Searching...
No Matches
JSWebsocketServer.hxx
Go to the documentation of this file.
1
37#include <emscripten.h>
38#include <emscripten/bind.h>
39#include <emscripten/val.h>
40
41#include <memory>
42
44
46{
47public:
48 JSWebsocketServer(CanHubFlow *hflow, int port, string static_dir)
49 : canHub_(hflow)
50 {
51 if (!static_dir.empty())
52 {
53 string script = "Module.static_dir = '" + static_dir + "';\n";
54 emscripten_run_script(script.c_str());
55 }
56 EM_ASM_(
57 {
58 var WebSocketServer = require('websocket').server;
59 var http = require('http');
60 var ecstatic = require('ecstatic');
61 if (Module.static_dir)
62 {
63 var serverImpl =
64 ecstatic({root : Module.static_dir, gzip : true});
65 }
66 else
67 {
68 var serverImpl = function(request, response){
69 // process HTTP request. Since we're writing just
70 // WebSockets server we don't have to implement
71 // anything.
72 };
73 }
74 var server = http.createServer(serverImpl);
75 console.log('try to listen on ', $0);
76 server.listen($0, function()
77 {
78 console.log(
79 'websocket server: listening on port ' + $0);
80 });
81 console.log('ws: listen done ', $0);
82
83 // create the server
84 wsServer = new WebSocketServer({httpServer : server});
85
86 // WebSocket server
87 wsServer.on('request', function(request)
88 {
89 var connection = request.accept(null, request.origin);
90 var client_port = new Module.JSHubPort($1,
91 function(gc_text)
92 {
93 var json = JSON.stringify(
94 {type : 'gc_can_frame', data : gc_text});
95 connection.sendUTF(json);
96 });
97 console.log('websocket client ',
98 client_port.get_port_num(), 'connected');
99 connection.on('message', function(message)
100 {
101 try
102 {
103 var json = JSON.parse(message.utf8Data);
104 }
105 catch (e)
106 {
107 console.log(
108 'This doesnt look like a valid JSON: ',
109 message.data, ' raw msg ', message);
110 return;
111 }
112 if (json.type === 'gc_can_frame')
113 {
114 // Send can frame data to the hub port
115 client_port.recv(json.data);
116 }
117 else
118 {
119 console.log('Unknown type ', message.type);
120 }
121 });
122 connection.on('close', function(connection)
123 {
124 console.log('websocket client ',
125 client_port.get_port_num(), 'disconnected');
126 client_port.pause();
127 });
128 connection.on('resume', function(connection)
129 {
130 console.log('websocket client ',
131 client_port.get_port_num(), ' resumed');
132 client_port.resume();
133 });
134 connection.on('pause', function(connection)
135 {
136 console.log('websocket client ',
137 client_port.get_port_num(), ' paused');
138 client_port.pause();
139 });
140 var ignevent = function(evname)
141 {
142 connection.on(evname, function(connection)
143 {
144 console.log(
145 'websocket ingoring event ', evname);
146 });
147 };
148 ignevent('drain');
149 });
150 },
151 port, (unsigned long)canHub_);
152 }
153
154private:
155 CanHubFlow *canHub_;
156};
Null null("/dev/null")
Filesystem node for the null device.