yanic/websocketserver/server.go

120 lines
2.0 KiB
Go
Raw Normal View History

package websocketserver
2016-02-19 11:13:30 +01:00
import (
"log"
"net/http"
"golang.org/x/net/websocket"
)
//Server struct
type Server struct {
2016-02-19 11:13:30 +01:00
pattern string
clients map[int]*Client
addCh chan *Client
delCh chan *Client
2016-02-25 21:24:54 +01:00
sendAllCh chan interface{}
closeCh chan bool
2016-02-19 11:13:30 +01:00
errCh chan error
}
2016-02-25 21:24:54 +01:00
//NewServer creates a new server
func NewServer(pattern string) *Server {
clients := make(map[int]*Client)
addCh := make(chan *Client)
delCh := make(chan *Client)
2016-02-25 21:24:54 +01:00
sendAllCh := make(chan interface{})
closeCh := make(chan bool)
2016-02-19 11:13:30 +01:00
errCh := make(chan error)
return &Server{
2016-02-19 11:13:30 +01:00
pattern,
clients,
addCh,
delCh,
sendAllCh,
closeCh,
2016-02-19 11:13:30 +01:00
errCh,
}
}
2016-02-25 21:24:54 +01:00
//Add a listen client
func (s *Server) Add(c *Client) {
2016-02-19 11:13:30 +01:00
s.addCh <- c
}
2016-02-25 21:24:54 +01:00
//Del a listen client
func (s *Server) Del(c *Client) {
2016-02-19 11:13:30 +01:00
s.delCh <- c
}
2016-02-25 21:24:54 +01:00
//SendAll to all listen clients a msg
func (s *Server) SendAll(msg interface{}) {
s.sendAllCh <- msg
2016-02-19 11:13:30 +01:00
}
2016-02-25 21:24:54 +01:00
//Close stops server
func (s *Server) Close() {
s.closeCh <- true
2016-02-19 11:13:30 +01:00
}
//Err send to server
func (s *Server) Err(err error) {
2016-02-19 11:13:30 +01:00
s.errCh <- err
}
2016-02-25 21:24:54 +01:00
func (s *Server) sendAll(msg interface{}) {
2016-02-19 11:13:30 +01:00
for _, c := range s.clients {
2016-02-25 21:24:54 +01:00
c.Write(msg)
2016-02-19 11:13:30 +01:00
}
}
// Listen and serve.
// It serves client connection and broadcast request.
func (s *Server) Listen() {
2016-02-19 11:13:30 +01:00
log.Println("Listening Server...")
2016-02-19 11:13:30 +01:00
// websocket handler
onConnected := func(ws *websocket.Conn) {
defer func() {
err := ws.Close()
if err != nil {
s.errCh <- err
}
}()
client := NewClient(ws, s)
2016-02-19 11:13:30 +01:00
s.Add(client)
client.Listen()
}
http.Handle(s.pattern, websocket.Handler(onConnected))
log.Println("Created handler")
for {
select {
// Add new a client
case c := <-s.addCh:
log.Println("Added new client")
s.clients[c.id] = c
log.Println("Now", len(s.clients), "clients connected.")
// del a client
case c := <-s.delCh:
log.Println("Delete client")
delete(s.clients, c.id)
// broadcast message for all clients
2016-02-25 21:24:54 +01:00
case msg := <-s.sendAllCh:
s.sendAll(msg)
2016-02-19 11:13:30 +01:00
case err := <-s.errCh:
log.Println("Error:", err.Error())
case <-s.closeCh:
2016-02-19 11:13:30 +01:00
return
}
}
}