yanic/websocketserver/server.go

126 lines
2.1 KiB
Go
Raw Normal View History

package websocketserver
2016-02-19 10:13:30 +00:00
import (
2016-02-25 22:30:17 +00:00
"fmt"
2016-02-19 10:13:30 +00:00
"log"
"net/http"
"golang.org/x/net/websocket"
)
//Server struct
type Server struct {
2016-02-19 10:13:30 +00:00
pattern string
clients map[int]*Client
addCh chan *Client
delCh chan *Client
2016-02-25 20:24:54 +00:00
sendAllCh chan interface{}
closeCh chan bool
2016-02-19 10:13:30 +00:00
errCh chan error
}
2016-02-25 20:24:54 +00: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 20:24:54 +00:00
sendAllCh := make(chan interface{})
closeCh := make(chan bool)
2016-02-19 10:13:30 +00:00
errCh := make(chan error)
return &Server{
2016-02-19 10:13:30 +00:00
pattern,
clients,
addCh,
delCh,
sendAllCh,
closeCh,
2016-02-19 10:13:30 +00:00
errCh,
}
}
2016-02-25 20:24:54 +00:00
//Add a listen client
func (s *Server) Add(c *Client) {
2016-02-19 10:13:30 +00:00
s.addCh <- c
}
2016-02-25 20:24:54 +00:00
//Del a listen client
func (s *Server) Del(c *Client) {
2016-02-19 10:13:30 +00:00
s.delCh <- c
}
2016-02-25 20:24:54 +00:00
//SendAll to all listen clients a msg
func (s *Server) SendAll(msg interface{}) {
s.sendAllCh <- msg
2016-02-19 10:13:30 +00:00
}
2016-02-25 20:24:54 +00:00
//Close stops server
func (s *Server) Close() {
s.closeCh <- true
2016-02-19 10:13:30 +00:00
}
//Err send to server
func (s *Server) Err(err error) {
2016-02-19 10:13:30 +00:00
s.errCh <- err
}
2016-02-25 20:24:54 +00:00
func (s *Server) sendAll(msg interface{}) {
2016-02-19 10:13:30 +00:00
for _, c := range s.clients {
2016-02-25 20:24:54 +00:00
c.Write(msg)
2016-02-19 10:13:30 +00:00
}
}
// Listen and serve.
// It serves client connection and broadcast request.
func (s *Server) Listen() {
2016-02-19 10:13:30 +00:00
log.Println("Listening Server...")
2016-02-19 10:13:30 +00: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 10:13:30 +00:00
s.Add(client)
2016-02-25 22:30:17 +00:00
defer func() {
s.Del(client)
err := fmt.Errorf("Client %d is disconnected.", client.id)
s.Err(err)
}()
2016-02-19 10:13:30 +00:00
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 20:24:54 +00:00
case msg := <-s.sendAllCh:
s.sendAll(msg)
2016-02-19 10:13:30 +00:00
case err := <-s.errCh:
log.Println("Error:", err.Error())
case <-s.closeCh:
2016-02-19 10:13:30 +00:00
return
}
}
}