This repository has been archived by the owner on Aug 24, 2019. It is now read-only.
/
main.go
114 lines (94 loc) · 1.89 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
package main
import (
"bufio"
"code.google.com/p/go.net/websocket"
"fmt"
"github.com/scottferg/goat"
"os"
)
var (
g *goat.Goat
pool *connectionPool
)
type socketConnection struct {
socket *websocket.Conn
messages chan string
}
type connectionPool struct {
pool map[*socketConnection]bool
register chan *socketConnection
unregister chan *socketConnection
broadcast chan string
}
func NewConnectionPool() *connectionPool {
return &connectionPool{
pool: make(map[*socketConnection]bool),
register: make(chan *socketConnection),
unregister: make(chan *socketConnection),
broadcast: make(chan string),
}
}
func (c *connectionPool) run() {
for {
select {
case sc := <-c.register:
c.pool[sc] = true
case sc := <-c.unregister:
delete(c.pool, sc)
close(sc.messages)
case message := <-c.broadcast:
for sc := range c.pool {
sc.write(message)
}
}
}
}
func (s *socketConnection) listen() {
for {
var raw string
err := websocket.Message.Receive(s.socket, &raw)
if err != nil {
break
}
}
}
func (s *socketConnection) write(message string) {
err := websocket.Message.Send(s.socket, message)
if err != nil {
return
}
}
func handleSocket(ws *websocket.Conn) {
s := &socketConnection{
socket: ws,
}
defer func() {
if err := s.socket.Close(); err != nil {
fmt.Println("Websocket could not be closed: ", err.Error())
}
}()
pool.register <- s
client := s.socket.Request().RemoteAddr
fmt.Println("Client connected: ", client)
s.listen()
}
func readInput() {
bio := bufio.NewReader(os.Stdin)
for {
line, err := bio.ReadString('\n')
if err != nil {
fmt.Println(err.Error())
}
pool.broadcast <- line
}
}
func main() {
g = goat.NewGoat()
g.RegisterRoute("/", "socket", goat.GET, websocket.Server{
Handler: handleSocket,
})
pool = NewConnectionPool()
go pool.run()
go g.ListenAndServe("5050")
readInput()
}