-
Notifications
You must be signed in to change notification settings - Fork 0
/
netUse.go
80 lines (67 loc) · 1.23 KB
/
netUse.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
package main
import (
"fmt"
"io"
"log"
"net"
"net/http"
"golang.org/x/net/websocket"
)
var partner = make(chan io.ReadWriteCloser)
func match(c io.ReadWriteCloser) {
fmt.Fprint(c, "Waiting for a partner...")
select {
case partner <- c:
// now handled by the other goroutine
case p := <-partner:
chat(p, c)
}
}
func chat(a, b io.ReadWriteCloser) {
fmt.Fprintln(a, "Found one! Say hi.")
fmt.Fprintln(b, "Found one! Say hi.")
go io.Copy(a, b)
io.Copy(b, a)
}
type socket struct {
io.ReadWriter
done chan bool
}
func (s socket) Close() error {
s.done <- true
return nil
}
func socketHandler(ws *websocket.Conn) {
s := socket{ws, make(chan bool)}
go match(s)
<-s.done
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello world")
}
func netMain() {
listenAddr := "localhost:4000"
go netListen()
http.HandleFunc("/", rootHandler)
http.Handle("/socket", websocket.Handler(socketHandler))
err := http.ListenAndServe(listenAddr, nil)
if err != nil {
log.Fatal(err)
}
}
func netListen() {
l, err := net.Listen("tcp", "localhost:4001")
if err != nil {
log.Fatal(err)
}
for {
c, err := l.Accept()
if err != nil {
log.Fatal(err)
}
go match(c)
}
}
func main() {
netMain()
}