clients.go 997 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "sync"
  6. "sync/atomic"
  7. "git.ali33.ru/fcg-xvii/go-tools/containers/concurrent"
  8. "git.ali33.ru/fcg-xvii/go-tools/json"
  9. "github.com/gorilla/websocket"
  10. )
  11. func NewWSClients() *WSClients {
  12. return &WSClients{
  13. List: concurrent.NewList(),
  14. rStore: new(sync.Map),
  15. }
  16. }
  17. type WSClients struct {
  18. *concurrent.List
  19. rStore *sync.Map
  20. counter uint32
  21. }
  22. func (s *WSClients) Broadcast(mes json.Map) {
  23. for e := s.First(); e != nil; e = e.Next() {
  24. e.Val().(*WSClient).SendSingle(mes)
  25. }
  26. }
  27. func (s *WSClients) clientConnected(conn *websocket.Conn) *WSClient {
  28. cctx, cancel := context.WithCancel(context.Background())
  29. cl := &WSClient{
  30. conn: conn,
  31. clients: s,
  32. ctx: cctx,
  33. cancel: cancel,
  34. }
  35. s.PushBack(cl)
  36. return cl
  37. }
  38. func (s *WSClients) clientDisconnected(cl *WSClient) {
  39. log.Println("DISCONNECTED")
  40. if e := s.Search(cl); e != nil {
  41. s.Remove(e)
  42. }
  43. }
  44. func (s *WSClients) nextID() int64 {
  45. return int64(atomic.AddUint32(&s.counter, 1))
  46. }