hub.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package util
  2. import (
  3. "bufio"
  4. "fmt"
  5. "net"
  6. "os"
  7. "strings"
  8. "sync"
  9. )
  10. // Hub is a helper to handle one to many chat
  11. type Hub struct {
  12. conns map[string]net.Conn
  13. lock sync.RWMutex
  14. }
  15. // NewHub builds a new hub
  16. func NewHub() *Hub {
  17. return &Hub{conns: make(map[string]net.Conn)}
  18. }
  19. // Register adds a new conn to the Hub
  20. func (h *Hub) Register(conn net.Conn) {
  21. fmt.Printf("Connected to %s\n", conn.RemoteAddr())
  22. h.lock.Lock()
  23. defer h.lock.Unlock()
  24. h.conns[conn.RemoteAddr().String()] = conn
  25. go h.readLoop(conn)
  26. }
  27. func (h *Hub) readLoop(conn net.Conn) {
  28. b := make([]byte, bufSize)
  29. for {
  30. n, err := conn.Read(b)
  31. if err != nil {
  32. h.unregister(conn)
  33. return
  34. }
  35. fmt.Printf("Got message: %s\n", string(b[:n]))
  36. }
  37. }
  38. func (h *Hub) unregister(conn net.Conn) {
  39. h.lock.Lock()
  40. defer h.lock.Unlock()
  41. delete(h.conns, conn.RemoteAddr().String())
  42. err := conn.Close()
  43. if err != nil {
  44. fmt.Println("Failed to disconnect", conn.RemoteAddr(), err)
  45. } else {
  46. fmt.Println("Disconnected ", conn.RemoteAddr())
  47. }
  48. }
  49. func (h *Hub) broadcast(msg []byte) {
  50. h.lock.RLock()
  51. defer h.lock.RUnlock()
  52. for _, conn := range h.conns {
  53. _, err := conn.Write(msg)
  54. if err != nil {
  55. fmt.Printf("Failed to write message to %s: %v\n", conn.RemoteAddr(), err)
  56. }
  57. }
  58. }
  59. // Chat starts the stdin readloop to dispatch messages to the hub
  60. func (h *Hub) Chat() {
  61. reader := bufio.NewReader(os.Stdin)
  62. for {
  63. msg, err := reader.ReadString('\n')
  64. Check(err)
  65. if strings.TrimSpace(msg) == "exit" {
  66. return
  67. }
  68. h.broadcast([]byte(msg))
  69. }
  70. }