application.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package rest_websocket
  2. import (
  3. "context"
  4. "log"
  5. )
  6. func NewApplication(ctx context.Context) *Application {
  7. app := &Application{
  8. ctx: ctx,
  9. chConnect: make(chan *SocketServer),
  10. chDisconnect: make(chan *SocketServer),
  11. }
  12. go app.work()
  13. return app
  14. }
  15. type Application struct {
  16. sockets []*SocketServer
  17. ctx context.Context
  18. chConnect chan *SocketServer
  19. chDisconnect chan *SocketServer
  20. }
  21. func (s *Application) Connect() chan<- *SocketServer {
  22. return s.chConnect
  23. }
  24. func (s *Application) Disconnect() chan<- *SocketServer {
  25. return s.chDisconnect
  26. }
  27. func (s *Application) work() {
  28. for {
  29. select {
  30. case <-s.ctx.Done():
  31. return
  32. case socket, ok := <-s.chConnect:
  33. if !ok {
  34. return
  35. }
  36. log.Println("CH-CONNECT")
  37. s.addSocket(socket)
  38. case socket := <-s.chDisconnect:
  39. log.Println("CH-DISCONNECT")
  40. for i, sock := range s.sockets {
  41. if sock == socket {
  42. s.sockets[i] = nil
  43. break
  44. }
  45. }
  46. }
  47. }
  48. }
  49. func (s *Application) searchFree() (int, bool) {
  50. for i, sock := range s.sockets {
  51. if sock == nil {
  52. return i, true
  53. }
  54. }
  55. return -1, false
  56. }
  57. func (s *Application) addSocket(socket *SocketServer) {
  58. log.Println("ADD_SOCKET", socket)
  59. // ищем свободный слот
  60. index, free := s.searchFree()
  61. if !free {
  62. sockets := make([]*SocketServer, len(s.sockets)+50)
  63. copy(sockets, s.sockets)
  64. sockets[len(s.sockets)] = socket
  65. } else {
  66. s.sockets[index] = socket
  67. }
  68. }