listener.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2017 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package net
  15. import (
  16. "fmt"
  17. "net"
  18. "sync"
  19. "github.com/fatedier/golib/errors"
  20. )
  21. // InternalListener is a listener that can be used to accept connections from
  22. // other goroutines.
  23. type InternalListener struct {
  24. acceptCh chan net.Conn
  25. closed bool
  26. mu sync.Mutex
  27. }
  28. func NewInternalListener() *InternalListener {
  29. return &InternalListener{
  30. acceptCh: make(chan net.Conn, 128),
  31. }
  32. }
  33. func (l *InternalListener) Accept() (net.Conn, error) {
  34. conn, ok := <-l.acceptCh
  35. if !ok {
  36. return nil, fmt.Errorf("listener closed")
  37. }
  38. return conn, nil
  39. }
  40. func (l *InternalListener) PutConn(conn net.Conn) error {
  41. err := errors.PanicToError(func() {
  42. select {
  43. case l.acceptCh <- conn:
  44. default:
  45. conn.Close()
  46. }
  47. })
  48. if err != nil {
  49. return fmt.Errorf("put conn error: listener is closed")
  50. }
  51. return nil
  52. }
  53. func (l *InternalListener) Close() error {
  54. l.mu.Lock()
  55. defer l.mu.Unlock()
  56. if !l.closed {
  57. close(l.acceptCh)
  58. l.closed = true
  59. }
  60. return nil
  61. }
  62. func (l *InternalListener) Addr() net.Addr {
  63. return &InternalAddr{}
  64. }
  65. type InternalAddr struct{}
  66. func (ia *InternalAddr) Network() string {
  67. return "internal"
  68. }
  69. func (ia *InternalAddr) String() string {
  70. return "internal"
  71. }