golang-lib/websocket/server.go

76 lines
1.4 KiB
Go
Raw Normal View History

2017-10-25 18:42:44 +02:00
package websocket
import (
"net/http"
"sync"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
)
type Server struct {
msgChanIn chan *Message
clients map[string]*Client
clientsMutex sync.Mutex
2017-10-27 19:40:42 +02:00
sessionManager *SessionManager
2017-10-25 18:42:44 +02:00
upgrader websocket.Upgrader
}
2017-10-27 19:40:42 +02:00
func NewServer(msgChanIn chan *Message, sessionManager *SessionManager) *Server {
2017-10-25 18:42:44 +02:00
return &Server{
clients: make(map[string]*Client),
msgChanIn: msgChanIn,
2017-10-27 19:40:42 +02:00
sessionManager: sessionManager,
2017-10-25 18:42:44 +02:00
upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
},
}
}
func (s *Server) Handler(w http.ResponseWriter, r *http.Request) {
conn, err := s.upgrader.Upgrade(w, r, nil)
if err != nil {
2017-10-27 19:40:42 +02:00
log.Info(err)
2017-10-25 18:42:44 +02:00
return
}
client := NewClient(s, conn)
defer client.Close()
client.Listen()
}
func (s *Server) AddClient(c *Client) {
if c == nil {
return
}
if id := c.GetID(); id != "" {
s.clientsMutex.Lock()
s.clients[id] = c
2017-10-27 19:40:42 +02:00
s.clientsMutex.Unlock()
if s.sessionManager != nil {
s.sessionManager.Init(c)
}
2017-10-25 18:42:44 +02:00
}
}
func (s *Server) DelClient(c *Client) {
if c == nil {
return
}
if id := c.GetID(); id != "" {
s.clientsMutex.Lock()
delete(s.clients, id)
s.clientsMutex.Unlock()
2017-10-27 19:40:42 +02:00
if s.sessionManager != nil {
s.sessionManager.Remove(c)
}
2017-10-25 18:42:44 +02:00
}
}
2018-04-26 21:24:42 +02:00
func (s *Server) SendAll(msg *Message) {
s.clientsMutex.Lock()
defer s.clientsMutex.Unlock()
for _, c := range s.clients {
c.Write(msg)
}
}