Newer
Older
// file system to load / look at our available modules / edit them
const fs = require('fs')
// express serves files, http makes the connection
const app = require('express')()
const http = require('http').Server(app)
// websocket, to share program representations with the client (and back)
const WebSocket = require('ws')
/*
SERVER AND WS SETUP
*/
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
var program = null
var sckt = null
function startHttp() {
// serving this handful of static files
app.get('/', (req, res) => {
console.log('client req /')
res.sendFile(__dirname + '/client/index.html')
})
app.get('/:file', (req, res) => {
console.log('client req', req.params.file)
res.sendFile(__dirname + '/client/' + req.params.file)
})
// through this window
http.listen(8080, () => {
console.log('listening on 8080 for static files')
})
}
function startWs() {
// and listening for requests here
const wss = new WebSocket.Server({ port: 8081 })
wss.on('connection', (ws) => {
sckt = ws
// say hello
socketSend('console', 'hello client')
// send current config as list of all modules
uiInit()
console.log('socket open on 8081')
ws.on('message', (evt) => {
socketRecv(evt)
})
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
}
function socketRecv(evt) {
var recv = JSON.parse(evt)
var type = recv.type
var data = recv.data
//console.log('RECV', recv)
// bang thru
switch (type) {
case 'console':
console.log('RECV CONSOLE:', data)
break
case 'get menu':
var tree = buildMenu()
socketSend('put menu', tree)
break
case 'add module':
addModule(data)
break
case 'put state':
changeState(data)
break
case 'put link':
putLink(data)
// id:output > id:input
break
case 'put ui':
changeUi(data)
break
case 'rm link':
// id:output > id:input
break
default:
console.log('ERR server recv with non recognized type', recv)
break
}
}
function socketSend(type, data) {
if (sckt) {
var msg = {
type: type,
data: data
}
//console.log('SEND', msg)
sckt.send(JSON.stringify(msg))
}
}
function assignProgram(prgm){
program = prgm
}
// runs when browser first loads
function uiInit(){
// make reps from program and send the list
console.log("BRWSER LOADED")
console.log(program)
}