-
Notifications
You must be signed in to change notification settings - Fork 3
/
websocket.go
68 lines (63 loc) · 1.58 KB
/
websocket.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
package main
import (
"fmt"
"io"
"os"
"sync"
"time"
"github.com/gorilla/websocket"
)
func readFromRemoteStdout(c *websocket.Conn, done *chan bool, pongWait time.Duration) {
defer func() { *done <- true }()
c.SetReadDeadline(time.Now().Add(pongWait))
c.SetPongHandler(func(string) error { c.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
mt, r, err := c.NextReader()
if websocket.IsCloseError(err,
websocket.CloseNormalClosure, // Normal.
) {
return
}
if err != nil {
fmt.Printf("nextreader: %v\n", err)
return
}
if mt != websocket.BinaryMessage {
fmt.Println("binary message")
return
}
if _, err := io.Copy(os.Stdout, r); err != nil {
fmt.Printf("Reading from websocket: %v\n", err)
return
}
}
}
func writeToRemoteStdin(c *websocket.Conn, done *chan bool, writeMutex *sync.Mutex, writeWait time.Duration) {
defer func() { *done <- true }()
for {
var input []byte = make([]byte, 1)
os.Stdin.Read(input)
writeMutex.Lock()
c.SetWriteDeadline(time.Now().Add(writeWait))
err := c.WriteMessage(websocket.BinaryMessage, append([]byte{0}, input...))
writeMutex.Unlock()
if err != nil {
fmt.Println("write:", err)
return
}
}
}
func sendPingMessages(c *websocket.Conn, done *chan bool, writeWait time.Duration, pingPeriod time.Duration) {
defer func() { *done <- true }()
ticker := time.NewTicker(pingPeriod)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := c.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(writeWait)); err != nil {
fmt.Println("ping:", err)
return
}
}
}
}