server.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. package uiserver
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "sync"
  7. )
  8. // Worker handles a single connection, providing updates to the clients
  9. type Worker struct {
  10. Update chan interface{} // this is called whenever a worker should update
  11. Exit chan interface{} // this is called to force the worker to Close
  12. Conn net.Conn
  13. }
  14. // NewWorker creates a new Worker from an ongoing connection
  15. func NewWorker(conn net.Conn) Worker {
  16. w := Worker{Conn: conn}
  17. w.Update = make(chan interface{}, 10)
  18. w.Exit = make(chan interface{})
  19. return w
  20. }
  21. func (w *Worker) send(obj interface{}) error {
  22. marshalled, err := json.Marshal(obj)
  23. if err != nil {
  24. return err
  25. }
  26. marshalled = append(marshalled, byte('\n'))
  27. _, err = w.Conn.Write(marshalled)
  28. return err
  29. }
  30. // Work loops on Worker channel to do what is needed
  31. func (w *Worker) Work() {
  32. for {
  33. select {
  34. case <-w.Exit:
  35. w.Conn.Close()
  36. return
  37. case obj := <-w.Update:
  38. err := w.send(obj)
  39. if err != nil {
  40. w.Conn.Close()
  41. return
  42. }
  43. }
  44. }
  45. }
  46. // NetUI handles a server for the protocol documented in this package
  47. // the API is designed so to make it possible to attach it to multiple
  48. // listeners, despite this is NOT possible at the moment
  49. type NetUI struct {
  50. Object interface{}
  51. workers []Worker
  52. workersMutex sync.Mutex
  53. sock *net.Listener
  54. sockMu sync.Mutex
  55. exit chan interface{}
  56. }
  57. // protocolHello is the hello message that the server will give to clients
  58. // a server doesn't expect any introduction from clients
  59. // the hello message is useful to clients to recognize protocol version cleanly
  60. // the clients are guaranteed that the hello message will always be present in
  61. // future versions of the protocol, always terminated by a newline and of
  62. // exactly 15bytes
  63. var protocolHello = "DIRETTOFORO V1\n"
  64. // NewNetUI creates a NetUI object. Don't create it otherwise!
  65. // the parameter "obj" must be a pointer; if it's not a pointer, no error will
  66. // be raised but bad things could happen later
  67. func NewNetUI(obj interface{}) NetUI {
  68. exitchan := make(chan interface{})
  69. return NetUI{exit: exitchan, Object: obj}
  70. }
  71. // Update sends the new state to every connected client
  72. func (n *NetUI) Update() {
  73. todelete := make([]Worker, 0)
  74. n.workersMutex.Lock()
  75. for _, w := range n.workers {
  76. select {
  77. case w.Update <- n.Object:
  78. default:
  79. todelete = append(todelete, w)
  80. }
  81. }
  82. n.workersMutex.Unlock()
  83. for _, w := range todelete {
  84. n.removeWorker(w)
  85. }
  86. }
  87. // Close shuts the TCPserver down synchronously
  88. func (n *NetUI) Close() {
  89. n.sockMu.Lock()
  90. defer n.sockMu.Unlock()
  91. if n.sock != nil {
  92. (*n.sock).Close()
  93. }
  94. // for _, w := range n.workers {
  95. // close(w.Exit)
  96. // close(w.Update)
  97. // }
  98. }
  99. func (n *NetUI) removeWorker(worker Worker) error {
  100. n.workersMutex.Lock()
  101. err := n.removeWorkerNoLock(worker)
  102. n.workersMutex.Unlock()
  103. return err
  104. }
  105. func (n *NetUI) removeWorkerNoLock(worker Worker) error {
  106. fmt.Println("avevo una lista lunga", len(n.workers))
  107. i := -1
  108. for pos, w := range n.workers {
  109. if worker == w {
  110. i = pos
  111. break
  112. }
  113. }
  114. if i == -1 {
  115. return fmt.Errorf("No such worker")
  116. }
  117. n.workers[i] = n.workers[0]
  118. n.workers = n.workers[1:]
  119. fmt.Println("ora ho una lista lunga", len(n.workers))
  120. return nil
  121. }
  122. func (n *NetUI) addWorker(connworker Worker) {
  123. n.workersMutex.Lock()
  124. n.workers = append(n.workers, connworker)
  125. n.workersMutex.Unlock()
  126. }
  127. // Run does the heavy work, and is blocking. It expects a Listener (typically
  128. // got with net.Listener)
  129. // It will exit when NetUI.Close() is called or when an error on the socket
  130. // happens
  131. func (n *NetUI) Run(sock net.Listener) error {
  132. if n.sock != nil {
  133. return fmt.Errorf("More than one Run for a single NetUI is currently unsupported")
  134. }
  135. n.sockMu.Lock()
  136. n.sock = &sock
  137. n.sockMu.Unlock()
  138. defer sock.Close()
  139. for {
  140. conn, err := sock.Accept()
  141. if err != nil {
  142. return nil
  143. }
  144. // FIXME: performance problem here: we're waiting each client to be
  145. // validated before passing to sth else; we'd better run this in a
  146. // goroutine, but then the access to n.workers would be concurrent,
  147. // which is not allowed
  148. err = validateRequest(conn)
  149. if err != nil {
  150. continue
  151. }
  152. connworker := NewWorker(conn)
  153. connworker.Update <- n.Object
  154. n.addWorker(connworker)
  155. go connworker.Work()
  156. }
  157. }
  158. func validateRequest(conn net.Conn) error {
  159. _, err := conn.Write([]byte(protocolHello))
  160. if err != nil {
  161. conn.Close()
  162. return err
  163. }
  164. return nil
  165. }