pipes.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package pipes
  17. import (
  18. "net"
  19. )
  20. // NetPipe wraps net.Pipe in a signature returning an error
  21. func NetPipe() (net.Conn, net.Conn, error) {
  22. p1, p2 := net.Pipe()
  23. return p1, p2, nil
  24. }
  25. // TCPPipe creates an in process full duplex pipe based on a localhost TCP socket
  26. func TCPPipe() (net.Conn, net.Conn, error) {
  27. l, err := net.Listen("tcp", "127.0.0.1:0")
  28. if err != nil {
  29. return nil, nil, err
  30. }
  31. defer l.Close()
  32. var aconn net.Conn
  33. aerr := make(chan error, 1)
  34. go func() {
  35. var err error
  36. aconn, err = l.Accept()
  37. aerr <- err
  38. }()
  39. dconn, err := net.Dial("tcp", l.Addr().String())
  40. if err != nil {
  41. <-aerr
  42. return nil, nil, err
  43. }
  44. if err := <-aerr; err != nil {
  45. dconn.Close()
  46. return nil, nil, err
  47. }
  48. return aconn, dconn, nil
  49. }