github.com/klaytn/klaytn@v1.10.2/networks/p2p/simulations/pipes/pipes.go (about)

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