listener.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. // Custom listener
  22. type CustomListener struct {
  23. acceptCh chan net.Conn
  24. closed bool
  25. mu sync.Mutex
  26. }
  27. func NewCustomListener() *CustomListener {
  28. return &CustomListener{
  29. acceptCh: make(chan net.Conn, 64),
  30. }
  31. }
  32. func (l *CustomListener) Accept() (net.Conn, error) {
  33. conn, ok := <-l.acceptCh
  34. if !ok {
  35. return nil, fmt.Errorf("listener closed")
  36. }
  37. return conn, nil
  38. }
  39. func (l *CustomListener) PutConn(conn net.Conn) error {
  40. err := errors.PanicToError(func() {
  41. select {
  42. case l.acceptCh <- conn:
  43. default:
  44. conn.Close()
  45. }
  46. })
  47. return err
  48. }
  49. func (l *CustomListener) Close() error {
  50. l.mu.Lock()
  51. defer l.mu.Unlock()
  52. if !l.closed {
  53. close(l.acceptCh)
  54. l.closed = true
  55. }
  56. return nil
  57. }
  58. func (l *CustomListener) Addr() net.Addr {
  59. return (*net.TCPAddr)(nil)
  60. }