diff options
Diffstat (limited to 'sockets.go')
-rw-r--r-- | sockets.go | 27 |
1 files changed, 20 insertions, 7 deletions
@@ -1,6 +1,7 @@ | |||
1 | package main | 1 | package main |
2 | 2 | ||
3 | import ( | 3 | import ( |
4 | "context" | ||
4 | "io" | 5 | "io" |
5 | "log" | 6 | "log" |
6 | "net" | 7 | "net" |
@@ -8,7 +9,7 @@ import ( | |||
8 | "github.com/gorilla/websocket" | 9 | "github.com/gorilla/websocket" |
9 | ) | 10 | ) |
10 | 11 | ||
11 | func wsReader(wsconn *websocket.Conn, out chan []byte) { | 12 | func wsReader(wsconn *websocket.Conn, out chan []byte, ctx context.Context) { |
12 | for { | 13 | for { |
13 | messageType, p, err := wsconn.ReadMessage() | 14 | messageType, p, err := wsconn.ReadMessage() |
14 | if err != nil { | 15 | if err != nil { |
@@ -19,11 +20,16 @@ func wsReader(wsconn *websocket.Conn, out chan []byte) { | |||
19 | log.Println("error: wsReader: only binary messages are supported") | 20 | log.Println("error: wsReader: only binary messages are supported") |
20 | continue | 21 | continue |
21 | } | 22 | } |
22 | out <- p | 23 | select { |
24 | case out <- p: | ||
25 | continue | ||
26 | case <-ctx.Done(): | ||
27 | return | ||
28 | } | ||
23 | } | 29 | } |
24 | } | 30 | } |
25 | 31 | ||
26 | func socketReader(proxyconn net.Conn, out chan []byte) { | 32 | func socketReader(proxyconn net.Conn, out chan []byte, ctx context.Context) { |
27 | for { | 33 | for { |
28 | readBuffer := make([]byte, 2048) | 34 | readBuffer := make([]byte, 2048) |
29 | 35 | ||
@@ -37,16 +43,21 @@ func socketReader(proxyconn net.Conn, out chan []byte) { | |||
37 | return | 43 | return |
38 | } | 44 | } |
39 | 45 | ||
40 | out <- readBuffer[:i] | 46 | select { |
47 | case out <- readBuffer[:i]: | ||
48 | continue | ||
49 | case <-ctx.Done(): | ||
50 | return | ||
51 | } | ||
41 | } | 52 | } |
42 | } | 53 | } |
43 | 54 | ||
44 | func serviceBoth(wsconn *websocket.Conn, proxyconn net.Conn) { | 55 | func serviceBoth(wsconn *websocket.Conn, proxyconn net.Conn, ctx context.Context) { |
45 | sc := make(chan []byte) | 56 | sc := make(chan []byte) |
46 | wsc := make(chan []byte) | 57 | wsc := make(chan []byte) |
47 | 58 | ||
48 | go socketReader(proxyconn, sc) | 59 | go socketReader(proxyconn, sc, ctx) |
49 | go wsReader(wsconn, wsc) | 60 | go wsReader(wsconn, wsc, ctx) |
50 | 61 | ||
51 | for { | 62 | for { |
52 | select { | 63 | select { |
@@ -61,6 +72,8 @@ func serviceBoth(wsconn *websocket.Conn, proxyconn net.Conn) { | |||
61 | log.Printf("error: serviceBoth: %s", err) | 72 | log.Printf("error: serviceBoth: %s", err) |
62 | return | 73 | return |
63 | } | 74 | } |
75 | case <-ctx.Done(): | ||
76 | return | ||
64 | } | 77 | } |
65 | } | 78 | } |
66 | } | 79 | } |