github.com/keysonZZZ/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgNet/netTester/netTester.go (about) 1 package netTester 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "net" 8 "time" 9 10 "github.com/bronze1man/kmg/kmgNet" 11 ) 12 13 type DirectDialer func() (net.Conn, error) 14 type ListenNewer func() (net.Listener, error) 15 16 /* 17 func RunTcpTestWithListenAddr(listenAddr string,Dialer DirectDialer,debug bool){ 18 return RunTcpListenerDialerTest( 19 func()(net.Listener,error){ 20 return net.Listen("tcp",listenAddr) 21 }, 22 Dialer,debug) 23 } 24 */ 25 func RunTcpTestWithNetDialAndNetListener(listenAddr string, dialAddr string, debug bool) { 26 RunTcpListenerDialerTest( 27 func() (net.Listener, error) { 28 return net.Listen("tcp", listenAddr) 29 }, 30 func() (net.Conn, error) { 31 return net.Dial("tcp", dialAddr) 32 }, debug) 33 } 34 35 func RunTcpListenerDialerTest(listenerNewer ListenNewer, 36 Dialer DirectDialer, 37 debug bool) { 38 writeRead(listenerNewer, Dialer, debug) 39 time.Sleep(time.Microsecond) 40 readWrite(listenerNewer, Dialer, debug) 41 time.Sleep(time.Microsecond) 42 readOnly(listenerNewer, Dialer, debug) 43 time.Sleep(time.Microsecond) 44 writeOnly(listenerNewer, Dialer, debug) 45 time.Sleep(time.Microsecond) 46 dialOnly(listenerNewer, Dialer, debug) 47 time.Sleep(time.Microsecond) 48 thread(listenerNewer, Dialer, debug) 49 time.Sleep(time.Microsecond) 50 bigWrite(listenerNewer, Dialer, debug) 51 time.Sleep(time.Microsecond) 52 } 53 54 func mustNotError(err error) { 55 if err != nil { 56 panic(err) 57 } 58 } 59 60 func mustReadSame(r io.Reader, toWrite []byte) { 61 buf := make([]byte, len(toWrite)) 62 n, err := io.ReadAtLeast(r, buf, len(toWrite)) 63 mustNotError(err) 64 if !bytes.Equal(buf[:n], toWrite) { 65 panic(fmt.Errorf("read write data not match")) 66 return 67 } 68 } 69 70 func runEchoServer(listenerNewer ListenNewer) net.Listener { 71 return listenAccept(listenerNewer, func(c net.Conn) { 72 defer c.Close() 73 _, err := io.Copy(c, c) 74 if kmgNet.IsSocketCloseError(err) { 75 return 76 } 77 mustNotError(err) 78 }) 79 } 80 81 func listenAccept(listenerNewer ListenNewer, handler func(c net.Conn)) net.Listener { 82 listener, err := listenerNewer() 83 mustNotError(err) 84 go func() { 85 for { 86 c, err := listener.Accept() 87 if kmgNet.IsSocketCloseError(err) { 88 return 89 } 90 mustNotError(err) 91 go handler(c) 92 } 93 }() 94 return listener 95 }