-
Notifications
You must be signed in to change notification settings - Fork 11
/
kmactor.go
78 lines (73 loc) · 1.88 KB
/
kmactor.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
package kmactor
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
)
type kmactor struct {
version string
token string
upgrader websocket.Upgrader
count atomic.Uint32
birthtime time.Time
}
func (self *kmactor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
} else if !websocket.IsWebSocketUpgrade(r) {
fmt.Fprintf(w, "app: kmactor\r\n")
fmt.Fprintf(w, "version: %s\r\n", self.version)
fmt.Fprintf(w, "age: %s\r\n", time.Since(self.birthtime))
fmt.Fprintf(w, "process id: %d\r\n", os.Getpid())
fmt.Fprintf(w, "session count: %d\r\n", self.count.Load())
scheme := "ws"
if r.TLS != nil {
scheme = "wss"
}
fmt.Fprintf(w, "address: %s\r\n", (&url.URL{Scheme: scheme, Host: r.Host}).String())
if len(self.token) > 0 {
fmt.Fprintf(w, "token: %s\r\n", self.token)
}
} else if len(self.token) > 0 && self.token != r.URL.Query().Get("token") {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
} else if conn, err := self.upgrader.Upgrade(w, r, nil); err == nil {
defer conn.Close()
if self.count.CompareAndSwap(0, 1) {
defer self.count.CompareAndSwap(1, 0)
handled := 0
count := 0
width, height := GetScreenSize()
cmd := Command{}
log.Println("connected")
defer func() { log.Printf("handled %d/%d", handled, count) }()
for {
cmd.Reset()
if err = conn.ReadJSON(&cmd); err != nil {
break
} else if Play(&cmd, width, height) {
handled += 1
}
count += 1
}
} else {
log.Println("refused")
}
}
}
func Build(ver, token string) (http.Handler, error) {
return &kmactor{
version: ver,
token: token,
upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(*http.Request) bool { return true },
},
birthtime: time.Now(),
}, nil
}