-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
273 lines (234 loc) · 5.81 KB
/
main.go
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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package main
import (
"encoding/json"
"fmt"
"html/template"
"math/rand"
"net/http"
"os"
"time"
. "github.com/ctnieves/mipsgo/simulator"
"github.com/gorilla/websocket"
uuid "github.com/satori/go.uuid"
)
const (
pongWait = 60 * time.Second
pingPeriod = 30 * time.Second
)
type ClientManager struct {
clients map[*Client]bool
broadcast chan []byte
register chan *Client
unregister chan *Client
}
type Client struct {
id string
socket *websocket.Conn
send chan []byte
simulator Simulator
currentSource string
response Response
}
// Commands used in Requests
const (
RUN = "run"
STEP = "step"
WRITE_MEM = "write_memory"
CLEAR_MEM = "clear_memory"
)
type Request struct {
Sender string `json:"sender,omitempty"`
Source string `json:"source,omitempty"`
Command string `json:"command,omitempty"`
Memory string `json:"memory"`
}
type Response struct {
RegisterContents map[string]int32 `json:"registers"`
Output string `json:"output"`
Memory string `json:"memory"`
Data struct {
CurrentLine int `json:"current_line"`
} `json:"data"`
}
var manager = ClientManager{
broadcast: make(chan []byte),
register: make(chan *Client),
unregister: make(chan *Client),
clients: make(map[*Client]bool),
}
func (manager *ClientManager) start() {
for {
select {
case conn := <-manager.register:
conn.simulator = EmptySimulator()
manager.clients[conn] = true
case conn := <-manager.unregister:
if _, ok := manager.clients[conn]; ok {
close(conn.send)
delete(manager.clients, conn)
}
// sends message to all clients
case request := <-manager.broadcast:
for conn := range manager.clients {
select {
case conn.send <- request:
default:
close(conn.send)
delete(manager.clients, conn)
}
}
}
}
}
func (manager *ClientManager) send(message []byte, ignore *Client) {
for conn := range manager.clients {
if conn != ignore {
conn.send <- message
}
}
}
func (c *Client) read() {
defer func() {
manager.unregister <- c
c.socket.Close()
}()
//c.socket.SetReadDealine(time.Now().Add(pongWait))
//c.socket.SetPongHandler(func(string) error {
//c.socket.SetReadDeadline(time.Now().Add(pongWait))
//return nil
//})
for {
_, message, err := c.socket.ReadMessage()
// client most likely disconnected
if err != nil {
manager.unregister <- c
c.socket.Close()
break
}
req := Request{Sender: c.id}
err = json.Unmarshal(message, &req)
if req.Command == RUN || req.Command == STEP {
if c.currentSource != req.Source {
c.currentSource = req.Source
c.simulator.VM.MemoryPersistentReset()
c.simulator.SetSource(req.Source)
}
go c.remoteRun(req, req.Command)
} else if req.Command == WRITE_MEM {
hexString := req.Memory
c.simulator.VM.Memory.Write(hexString)
} else if req.Command == CLEAR_MEM {
req.Memory = ""
c.simulator.Init()
}
}
}
func (c *Client) write() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.socket.Close()
}()
for {
select {
case _, ok := <-c.send:
if !ok {
c.socket.WriteMessage(websocket.CloseMessage, []byte{})
}
case <-ticker.C:
if err := c.socket.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
return
}
}
}
}
func (c *Client) remoteRun(req Request, cmd string) {
defer c.simulator.ClearOutputs()
if !c.simulator.Running {
c.simulator.VM.MemoryPersistentReset()
c.simulator.SetSource(req.Source)
}
var err error = nil
if cmd == RUN {
err = c.simulator.Run()
if !c.simulator.Paused {
c.response.Output += "Run complete...\n"
}
} else if cmd == STEP {
c.simulator.Step()
}
if err != nil {
c.response.Output += err.Error() + "\n"
}
c.response.Memory = c.simulator.VM.Memory.ToText()
c.response.RegisterContents = c.simulator.VM.GetMappedRegisters()
for _, out := range c.simulator.VM.Outputs {
c.response.Output += out
}
c.response.Output += "\n"
c.response.Data.CurrentLine = c.simulator.GetCurrentLine()
resp, err := json.Marshal(c.response)
if err != nil {
fmt.Println("Error marshalling console output for browser")
} else {
c.socket.WriteMessage(websocket.TextMessage, resp)
// clear response
c.response = Response{}
}
}
func wsPage(res http.ResponseWriter, r *http.Request) {
conn, error := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}).Upgrade(res, r, nil)
if error != nil {
http.NotFound(res, r)
return
}
client := &Client{id: uuid.NewV4().String(), socket: conn, send: make(chan []byte)}
manager.register <- client
go client.read()
go client.write()
}
var templates = template.Must(template.New("temps").Funcs(template.FuncMap{
"minus": func(a, b int) int {
return a - b
},
"plus": func(a, b int) int {
return a + b
},
"rand": func(n int) int {
return rand.Intn(n)
},
"loop": func(n int) []int {
var arr = make([]int, n)
for i := 0; i < n; i++ {
arr[i] = i
}
return arr
},
}).ParseGlob("public/*.html"))
func indexHandler(w http.ResponseWriter, r *http.Request) {
templates.ExecuteTemplate(w, "index.html", nil)
}
func handleFileServers(directories []string) {
for _, dir := range directories {
d := http.FileServer(http.Dir("./public/" + dir))
http.Handle("/"+dir+"/", http.StripPrefix("/"+dir+"/", d))
}
}
func serveSingle(pattern string, filename string) {
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "public/"+filename)
})
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
go manager.start()
handleFileServers([]string{"css", "fonts", "js"})
http.HandleFunc("/", indexHandler)
http.HandleFunc("/index.html", indexHandler)
serveSingle("/favicon.ico", "public/favicon.ico")
http.HandleFunc("/ws", wsPage)
http.ListenAndServe(":"+port, nil)
}