golang-lib/websocket/server.go

81 lines
1.6 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"
)
// Server of websocket
2017-10-25 18:42:44 +02:00
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
}
// NewServer to get a new Server for websockets
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,
},
}
}
// Handler of websocket Server for binding on webserver
2017-10-25 18:42:44 +02:00
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) {
2017-10-25 18:42:44 +02:00
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) {
2017-10-25 18:42:44 +02:00
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
}
}
// SendAll to Send a message on every Client
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)
}
}