You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.4 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package peer
  2. import (
  3. "sync/atomic"
  4. "net"
  5. )
  6. /* Listener */
  7. type Listener interface {
  8. Connections() <-chan *Connection
  9. LocalAddress() *NetAddress
  10. Stop()
  11. }
  12. /* DefaultListener */
  13. type DefaultListener struct {
  14. listener net.Listener
  15. connections chan *Connection
  16. stopped uint32
  17. }
  18. const (
  19. DEFAULT_BUFFERED_CONNECTIONS = 10
  20. )
  21. func NewListener(protocol string, laddr string) Listener {
  22. ln, err := net.Listen(protocol, laddr)
  23. if err != nil { panic(err) }
  24. dl := &DefaultListener{
  25. listener: ln,
  26. connections: make(chan *Connection, DEFAULT_BUFFERED_CONNECTIONS),
  27. }
  28. go dl.listenHandler()
  29. return dl
  30. }
  31. func (l *DefaultListener) listenHandler() {
  32. for {
  33. conn, err := l.listener.Accept()
  34. if atomic.LoadUint32(&l.stopped) == 1 { return }
  35. // listener wasn't stopped,
  36. // yet we encountered an error.
  37. if err != nil { panic(err) }
  38. c := NewConnection(conn)
  39. l.connections <- c
  40. }
  41. // cleanup
  42. close(l.connections)
  43. for _ = range l.connections {
  44. // drain
  45. }
  46. }
  47. func (l *DefaultListener) Connections() <-chan *Connection {
  48. return l.connections
  49. }
  50. func (l *DefaultListener) LocalAddress() *NetAddress {
  51. return NewNetAddress(l.listener.Addr())
  52. }
  53. func (l *DefaultListener) Stop() {
  54. if atomic.CompareAndSwapUint32(&l.stopped, 0, 1) {
  55. l.listener.Close()
  56. }
  57. }