80 lines
1.1 KiB
Go
80 lines
1.1 KiB
Go
package testutil
|
|
|
|
import (
|
|
"net"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type Network struct {
|
|
lock sync.Mutex
|
|
// Current connections.
|
|
cConn net.Conn
|
|
sConn net.Conn
|
|
|
|
acceptQ chan net.Conn
|
|
}
|
|
|
|
func NewNetwork() *Network {
|
|
return &Network{
|
|
acceptQ: make(chan net.Conn, 1),
|
|
}
|
|
}
|
|
|
|
func (n *Network) Dial() net.Conn {
|
|
cc, sc := net.Pipe()
|
|
func() {
|
|
n.lock.Lock()
|
|
defer n.lock.Unlock()
|
|
if n.cConn != nil {
|
|
n.cConn.Close()
|
|
n.cConn = nil
|
|
}
|
|
select {
|
|
case n.acceptQ <- sc:
|
|
n.cConn = cc
|
|
default:
|
|
cc = nil
|
|
}
|
|
}()
|
|
return cc
|
|
}
|
|
|
|
func (n *Network) Accept() net.Conn {
|
|
var sc net.Conn
|
|
select {
|
|
case sc = <-n.acceptQ:
|
|
case <-time.After(time.Second):
|
|
return nil
|
|
}
|
|
|
|
func() {
|
|
n.lock.Lock()
|
|
defer n.lock.Unlock()
|
|
if n.sConn != nil {
|
|
n.sConn.Close()
|
|
n.sConn = nil
|
|
}
|
|
n.sConn = sc
|
|
}()
|
|
return sc
|
|
}
|
|
|
|
func (n *Network) CloseClient() {
|
|
n.lock.Lock()
|
|
defer n.lock.Unlock()
|
|
if n.cConn != nil {
|
|
n.cConn.Close()
|
|
n.cConn = nil
|
|
}
|
|
}
|
|
|
|
func (n *Network) CloseServer() {
|
|
n.lock.Lock()
|
|
defer n.lock.Unlock()
|
|
if n.sConn != nil {
|
|
n.sConn.Close()
|
|
n.sConn = nil
|
|
}
|
|
}
|