How to use Read method of conn Package

Best Gauge code snippet using conn.Read

latency_test.go

Source:latency_test.go Github

copy

Full Screen

...24 "sync"25 "testing"26 "time"27)28// bufConn is a net.Conn implemented by a bytes.Buffer (which is a ReadWriter).29type bufConn struct {30 *bytes.Buffer31}32func (bufConn) Close() error { panic("unimplemented") }33func (bufConn) LocalAddr() net.Addr { panic("unimplemented") }34func (bufConn) RemoteAddr() net.Addr { panic("unimplemented") }35func (bufConn) SetDeadline(t time.Time) error { panic("unimplemneted") }36func (bufConn) SetReadDeadline(t time.Time) error { panic("unimplemneted") }37func (bufConn) SetWriteDeadline(t time.Time) error { panic("unimplemneted") }38func restoreHooks() func() {39 s := sleep40 n := now41 return func() {42 sleep = s43 now = n44 }45}46func TestConn(t *testing.T) {47 defer restoreHooks()()48 // Constant time.49 now = func() time.Time { return time.Unix(123, 456) }50 // Capture sleep times for checking later.51 var sleepTimes []time.Duration52 sleep = func(t time.Duration) { sleepTimes = append(sleepTimes, t) }53 wantSleeps := func(want ...time.Duration) {54 if !reflect.DeepEqual(want, sleepTimes) {55 t.Fatalf("sleepTimes = %v; want %v", sleepTimes, want)56 }57 sleepTimes = nil58 }59 // Use a fairly high latency to cause a large BDP and avoid sleeps while60 // writing due to simulation of full buffers.61 latency := 1 * time.Second62 c, err := (&Network{Kbps: 1, Latency: latency, MTU: 5}).Conn(bufConn{&bytes.Buffer{}})63 if err != nil {64 t.Fatalf("Unexpected error creating connection: %v", err)65 }66 wantSleeps(latency) // Connection creation delay.67 // 1 kbps = 128 Bps. Divides evenly by 1 second using nanos.68 byteLatency := time.Duration(time.Second / 128)69 write := func(b []byte) {70 n, err := c.Write(b)71 if n != len(b) || err != nil {72 t.Fatalf("c.Write(%v) = %v, %v; want %v, nil", b, n, err, len(b))73 }74 }75 write([]byte{1, 2, 3, 4, 5}) // One full packet76 pkt1Time := latency + byteLatency*577 write([]byte{6}) // One partial packet78 pkt2Time := pkt1Time + byteLatency79 write([]byte{7, 8, 9, 10, 11, 12, 13}) // Two packets80 pkt3Time := pkt2Time + byteLatency*581 pkt4Time := pkt3Time + byteLatency*282 // No reads, so no sleeps yet.83 wantSleeps()84 read := func(n int, want []byte) {85 b := make([]byte, n)86 if rd, err := c.Read(b); err != nil || rd != len(want) {87 t.Fatalf("c.Read(<%v bytes>) = %v, %v; want %v, nil", n, rd, err, len(want))88 }89 if !reflect.DeepEqual(b[:len(want)], want) {90 t.Fatalf("read %v; want %v", b, want)91 }92 }93 read(1, []byte{1})94 wantSleeps(pkt1Time)95 read(1, []byte{2})96 wantSleeps()97 read(3, []byte{3, 4, 5})98 wantSleeps()99 read(2, []byte{6})100 wantSleeps(pkt2Time)101 read(2, []byte{7, 8})102 wantSleeps(pkt3Time)103 read(10, []byte{9, 10, 11})104 wantSleeps()105 read(10, []byte{12, 13})106 wantSleeps(pkt4Time)107}108func TestSync(t *testing.T) {109 defer restoreHooks()()110 // Infinitely fast CPU: time doesn't pass unless sleep is called.111 tn := time.Unix(123, 0)112 now = func() time.Time { return tn }113 sleep = func(d time.Duration) { tn = tn.Add(d) }114 // Simulate a 20ms latency network, then run sync across that and expect to115 // measure 20ms latency, or 10ms additional delay for a 30ms network.116 slowConn, err := (&Network{Kbps: 0, Latency: 20 * time.Millisecond, MTU: 5}).Conn(bufConn{&bytes.Buffer{}})117 if err != nil {118 t.Fatalf("Unexpected error creating connection: %v", err)119 }120 c, err := (&Network{Latency: 30 * time.Millisecond}).Conn(slowConn)121 if err != nil {122 t.Fatalf("Unexpected error creating connection: %v", err)123 }124 if c.(*conn).delay != 10*time.Millisecond {125 t.Fatalf("c.delay = %v; want 10ms", c.(*conn).delay)126 }127}128func TestSyncTooSlow(t *testing.T) {129 defer restoreHooks()()130 // Infinitely fast CPU: time doesn't pass unless sleep is called.131 tn := time.Unix(123, 0)132 now = func() time.Time { return tn }133 sleep = func(d time.Duration) { tn = tn.Add(d) }134 // Simulate a 10ms latency network, then attempt to simulate a 5ms latency135 // network and expect an error.136 slowConn, err := (&Network{Kbps: 0, Latency: 10 * time.Millisecond, MTU: 5}).Conn(bufConn{&bytes.Buffer{}})137 if err != nil {138 t.Fatalf("Unexpected error creating connection: %v", err)139 }140 errWant := "measured network latency (10ms) higher than desired latency (5ms)"141 if _, err := (&Network{Latency: 5 * time.Millisecond}).Conn(slowConn); err == nil || err.Error() != errWant {142 t.Fatalf("Conn() = _, %q; want _, %q", err, errWant)143 }144}145func TestListenerAndDialer(t *testing.T) {146 defer restoreHooks()()147 tn := time.Unix(123, 0)148 startTime := tn149 mu := &sync.Mutex{}150 now = func() time.Time {151 mu.Lock()152 defer mu.Unlock()153 return tn154 }155 // Use a fairly high latency to cause a large BDP and avoid sleeps while156 // writing due to simulation of full buffers.157 n := &Network{Kbps: 2, Latency: 1 * time.Second, MTU: 10}158 // 2 kbps = .25 kBps = 256 Bps159 byteLatency := func(n int) time.Duration {160 return time.Duration(n) * time.Second / 256161 }162 // Create a real listener and wrap it.163 l, err := net.Listen("tcp", "localhost:0")164 if err != nil {165 t.Fatalf("Unexpected error creating listener: %v", err)166 }167 defer l.Close()168 l = n.Listener(l)169 var serverConn net.Conn170 var scErr error171 scDone := make(chan struct{})172 go func() {173 serverConn, scErr = l.Accept()174 close(scDone)175 }()176 // Create a dialer and use it.177 clientConn, err := n.TimeoutDialer(net.DialTimeout)("tcp", l.Addr().String(), 2*time.Second)178 if err != nil {179 t.Fatalf("Unexpected error dialing: %v", err)180 }181 defer clientConn.Close()182 // Block until server's Conn is available.183 <-scDone184 if scErr != nil {185 t.Fatalf("Unexpected error listening: %v", scErr)186 }187 defer serverConn.Close()188 // sleep (only) advances tn. Done after connections established so sync detects zero delay.189 sleep = func(d time.Duration) {190 mu.Lock()191 defer mu.Unlock()192 if d > 0 {193 tn = tn.Add(d)194 }195 }196 seq := func(a, b int) []byte {197 buf := make([]byte, b-a)198 for i := 0; i < b-a; i++ {199 buf[i] = byte(i + a)200 }201 return buf202 }203 pkt1 := seq(0, 10)204 pkt2 := seq(10, 30)205 pkt3 := seq(30, 35)206 write := func(c net.Conn, b []byte) {207 n, err := c.Write(b)208 if n != len(b) || err != nil {209 t.Fatalf("c.Write(%v) = %v, %v; want %v, nil", b, n, err, len(b))210 }211 }212 write(serverConn, pkt1)213 write(serverConn, pkt2)214 write(serverConn, pkt3)215 write(clientConn, pkt3)216 write(clientConn, pkt1)217 write(clientConn, pkt2)218 if tn != startTime {219 t.Fatalf("unexpected sleep in write; tn = %v; want %v", tn, startTime)220 }221 read := func(c net.Conn, n int, want []byte, timeWant time.Time) {222 b := make([]byte, n)223 if rd, err := c.Read(b); err != nil || rd != len(want) {224 t.Fatalf("c.Read(<%v bytes>) = %v, %v; want %v, nil (read: %v)", n, rd, err, len(want), b[:rd])225 }226 if !reflect.DeepEqual(b[:len(want)], want) {227 t.Fatalf("read %v; want %v", b, want)228 }229 if !tn.Equal(timeWant) {230 t.Errorf("tn after read(%v) = %v; want %v", want, tn, timeWant)231 }232 }233 read(clientConn, len(pkt1)+1, pkt1, startTime.Add(n.Latency+byteLatency(len(pkt1))))234 read(serverConn, len(pkt3)+1, pkt3, tn) // tn was advanced by the above read; pkt3 is shorter than pkt1235 read(clientConn, len(pkt2), pkt2[:10], startTime.Add(n.Latency+byteLatency(len(pkt1)+10)))236 read(clientConn, len(pkt2), pkt2[10:], startTime.Add(n.Latency+byteLatency(len(pkt1)+len(pkt2))))237 read(clientConn, len(pkt3), pkt3, startTime.Add(n.Latency+byteLatency(len(pkt1)+len(pkt2)+len(pkt3))))238 read(serverConn, len(pkt1), pkt1, tn) // tn already past the arrival time due to prior reads239 read(serverConn, len(pkt2), pkt2[:10], tn)240 read(serverConn, len(pkt2), pkt2[10:], tn)241 // Sleep awhile and make sure the read happens disregarding previous writes242 // (lastSendEnd handling).243 sleep(10 * time.Second)244 write(clientConn, pkt1)245 read(serverConn, len(pkt1), pkt1, tn.Add(n.Latency+byteLatency(len(pkt1))))246 // Send, sleep longer than the network delay, then make sure the read happens247 // instantly.248 write(serverConn, pkt1)249 sleep(10 * time.Second)250 read(clientConn, len(pkt1), pkt1, tn)251}252func TestBufferBloat(t *testing.T) {253 defer restoreHooks()()254 // Infinitely fast CPU: time doesn't pass unless sleep is called.255 tn := time.Unix(123, 0)256 now = func() time.Time { return tn }257 // Capture sleep times for checking later.258 var sleepTimes []time.Duration259 sleep = func(d time.Duration) {260 sleepTimes = append(sleepTimes, d)261 tn = tn.Add(d)262 }263 wantSleeps := func(want ...time.Duration) error {264 if !reflect.DeepEqual(want, sleepTimes) {265 return fmt.Errorf("sleepTimes = %v; want %v", sleepTimes, want)266 }267 sleepTimes = nil268 return nil269 }270 n := &Network{Kbps: 8 /* 1KBps */, Latency: time.Second, MTU: 8}271 bdpBytes := (n.Kbps * 1024 / 8) * int(n.Latency/time.Second) // 1024272 c, err := n.Conn(bufConn{&bytes.Buffer{}})273 if err != nil {274 t.Fatalf("Unexpected error creating connection: %v", err)275 }276 wantSleeps(n.Latency) // Connection creation delay.277 write := func(n int, sleeps ...time.Duration) {278 if wt, err := c.Write(make([]byte, n)); err != nil || wt != n {279 t.Fatalf("c.Write(<%v bytes>) = %v, %v; want %v, nil", n, wt, err, n)280 }281 if err := wantSleeps(sleeps...); err != nil {282 t.Fatalf("After writing %v bytes: %v", n, err)283 }284 }285 read := func(n int, sleeps ...time.Duration) {286 if rd, err := c.Read(make([]byte, n)); err != nil || rd != n {287 t.Fatalf("c.Read(_) = %v, %v; want %v, nil", rd, err, n)288 }289 if err := wantSleeps(sleeps...); err != nil {290 t.Fatalf("After reading %v bytes: %v", n, err)291 }292 }293 write(8) // No reads and buffer not full, so no sleeps yet.294 read(8, time.Second+n.pktTime(8))295 write(bdpBytes) // Fill the buffer.296 write(1) // We can send one extra packet even when the buffer is full.297 write(n.MTU, n.pktTime(1)) // Make sure we sleep to clear the previous write.298 write(1, n.pktTime(n.MTU))299 write(n.MTU+1, n.pktTime(1), n.pktTime(n.MTU))300 tn = tn.Add(10 * time.Second) // Wait long enough for the buffer to clear.301 write(bdpBytes) // No sleeps required....

Full Screen

Full Screen

packets_test.go

Source:packets_test.go Github

copy

Full Screen

...14 "time"15)16var (17 errConnClosed = errors.New("connection is closed")18 errConnTooManyReads = errors.New("too many reads")19 errConnTooManyWrites = errors.New("too many writes")20)21// struct to mock a net.Conn for testing purposes22type mockConn struct {23 laddr net.Addr24 raddr net.Addr25 data []byte26 written []byte27 queuedReplies [][]byte28 closed bool29 read int30 reads int31 writes int32 maxReads int33 maxWrites int34}35func (m *mockConn) Read(b []byte) (n int, err error) {36 if m.closed {37 return 0, errConnClosed38 }39 m.reads++40 if m.maxReads > 0 && m.reads > m.maxReads {41 return 0, errConnTooManyReads42 }43 n = copy(b, m.data)44 m.read += n45 m.data = m.data[n:]46 return47}48func (m *mockConn) Write(b []byte) (n int, err error) {49 if m.closed {50 return 0, errConnClosed51 }52 m.writes++53 if m.maxWrites > 0 && m.writes > m.maxWrites {54 return 0, errConnTooManyWrites55 }56 n = len(b)57 m.written = append(m.written, b...)58 if n > 0 && len(m.queuedReplies) > 0 {59 m.data = m.queuedReplies[0]60 m.queuedReplies = m.queuedReplies[1:]61 }62 return63}64func (m *mockConn) Close() error {65 m.closed = true66 return nil67}68func (m *mockConn) LocalAddr() net.Addr {69 return m.laddr70}71func (m *mockConn) RemoteAddr() net.Addr {72 return m.raddr73}74func (m *mockConn) SetDeadline(t time.Time) error {75 return nil76}77func (m *mockConn) SetReadDeadline(t time.Time) error {78 return nil79}80func (m *mockConn) SetWriteDeadline(t time.Time) error {81 return nil82}83// make sure mockConn implements the net.Conn interface84var _ net.Conn = new(mockConn)85func newRWMockConn(sequence uint8) (*mockConn, *mysqlConn) {86 conn := new(mockConn)87 mc := &mysqlConn{88 buf: newBuffer(conn),89 cfg: NewConfig(),90 netConn: conn,91 closech: make(chan struct{}),92 maxAllowedPacket: defaultMaxAllowedPacket,93 sequence: sequence,94 }95 return conn, mc96}97func TestReadPacketSingleByte(t *testing.T) {98 conn := new(mockConn)99 mc := &mysqlConn{100 buf: newBuffer(conn),101 }102 conn.data = []byte{0x01, 0x00, 0x00, 0x00, 0xff}103 conn.maxReads = 1104 packet, err := mc.readPacket()105 if err != nil {106 t.Fatal(err)107 }108 if len(packet) != 1 {109 t.Fatalf("unexpected packet length: expected %d, got %d", 1, len(packet))110 }111 if packet[0] != 0xff {112 t.Fatalf("unexpected packet content: expected %x, got %x", 0xff, packet[0])113 }114}115func TestReadPacketWrongSequenceID(t *testing.T) {116 conn := new(mockConn)117 mc := &mysqlConn{118 buf: newBuffer(conn),119 }120 // too low sequence id121 conn.data = []byte{0x01, 0x00, 0x00, 0x00, 0xff}122 conn.maxReads = 1123 mc.sequence = 1124 _, err := mc.readPacket()125 if err != ErrPktSync {126 t.Errorf("expected ErrPktSync, got %v", err)127 }128 // reset129 conn.reads = 0130 mc.sequence = 0131 mc.buf = newBuffer(conn)132 // too high sequence id133 conn.data = []byte{0x01, 0x00, 0x00, 0x42, 0xff}134 _, err = mc.readPacket()135 if err != ErrPktSyncMul {136 t.Errorf("expected ErrPktSyncMul, got %v", err)137 }138}139func TestReadPacketSplit(t *testing.T) {140 conn := new(mockConn)141 mc := &mysqlConn{142 buf: newBuffer(conn),143 }144 data := make([]byte, maxPacketSize*2+4*3)145 const pkt2ofs = maxPacketSize + 4146 const pkt3ofs = 2 * (maxPacketSize + 4)147 // case 1: payload has length maxPacketSize148 data = data[:pkt2ofs+4]149 // 1st packet has maxPacketSize length and sequence id 0150 // ff ff ff 00 ...151 data[0] = 0xff152 data[1] = 0xff153 data[2] = 0xff154 // mark the payload start and end of 1st packet so that we can check if the155 // content was correctly appended156 data[4] = 0x11157 data[maxPacketSize+3] = 0x22158 // 2nd packet has payload length 0 and squence id 1159 // 00 00 00 01160 data[pkt2ofs+3] = 0x01161 conn.data = data162 conn.maxReads = 3163 packet, err := mc.readPacket()164 if err != nil {165 t.Fatal(err)166 }167 if len(packet) != maxPacketSize {168 t.Fatalf("unexpected packet length: expected %d, got %d", maxPacketSize, len(packet))169 }170 if packet[0] != 0x11 {171 t.Fatalf("unexpected payload start: expected %x, got %x", 0x11, packet[0])172 }173 if packet[maxPacketSize-1] != 0x22 {174 t.Fatalf("unexpected payload end: expected %x, got %x", 0x22, packet[maxPacketSize-1])175 }176 // case 2: payload has length which is a multiple of maxPacketSize177 data = data[:cap(data)]178 // 2nd packet now has maxPacketSize length179 data[pkt2ofs] = 0xff180 data[pkt2ofs+1] = 0xff181 data[pkt2ofs+2] = 0xff182 // mark the payload start and end of the 2nd packet183 data[pkt2ofs+4] = 0x33184 data[pkt2ofs+maxPacketSize+3] = 0x44185 // 3rd packet has payload length 0 and squence id 2186 // 00 00 00 02187 data[pkt3ofs+3] = 0x02188 conn.data = data189 conn.reads = 0190 conn.maxReads = 5191 mc.sequence = 0192 packet, err = mc.readPacket()193 if err != nil {194 t.Fatal(err)195 }196 if len(packet) != 2*maxPacketSize {197 t.Fatalf("unexpected packet length: expected %d, got %d", 2*maxPacketSize, len(packet))198 }199 if packet[0] != 0x11 {200 t.Fatalf("unexpected payload start: expected %x, got %x", 0x11, packet[0])201 }202 if packet[2*maxPacketSize-1] != 0x44 {203 t.Fatalf("unexpected payload end: expected %x, got %x", 0x44, packet[2*maxPacketSize-1])204 }205 // case 3: payload has a length larger maxPacketSize, which is not an exact206 // multiple of it207 data = data[:pkt2ofs+4+42]208 data[pkt2ofs] = 0x2a209 data[pkt2ofs+1] = 0x00210 data[pkt2ofs+2] = 0x00211 data[pkt2ofs+4+41] = 0x44212 conn.data = data213 conn.reads = 0214 conn.maxReads = 4215 mc.sequence = 0216 packet, err = mc.readPacket()217 if err != nil {218 t.Fatal(err)219 }220 if len(packet) != maxPacketSize+42 {221 t.Fatalf("unexpected packet length: expected %d, got %d", maxPacketSize+42, len(packet))222 }223 if packet[0] != 0x11 {224 t.Fatalf("unexpected payload start: expected %x, got %x", 0x11, packet[0])225 }226 if packet[maxPacketSize+41] != 0x44 {227 t.Fatalf("unexpected payload end: expected %x, got %x", 0x44, packet[maxPacketSize+41])228 }229}230func TestReadPacketFail(t *testing.T) {231 conn := new(mockConn)232 mc := &mysqlConn{233 buf: newBuffer(conn),234 closech: make(chan struct{}),235 }236 // illegal empty (stand-alone) packet237 conn.data = []byte{0x00, 0x00, 0x00, 0x00}238 conn.maxReads = 1239 _, err := mc.readPacket()240 if err != ErrInvalidConn {241 t.Errorf("expected ErrInvalidConn, got %v", err)242 }243 // reset244 conn.reads = 0245 mc.sequence = 0246 mc.buf = newBuffer(conn)247 // fail to read header248 conn.closed = true249 _, err = mc.readPacket()250 if err != ErrInvalidConn {251 t.Errorf("expected ErrInvalidConn, got %v", err)252 }253 // reset254 conn.closed = false255 conn.reads = 0256 mc.sequence = 0257 mc.buf = newBuffer(conn)258 // fail to read body259 conn.maxReads = 1260 _, err = mc.readPacket()261 if err != ErrInvalidConn {262 t.Errorf("expected ErrInvalidConn, got %v", err)263 }264}265// https://github.com/go-sql-driver/mysql/pull/801266// not-NUL terminated plugin_name in init packet267func TestRegression801(t *testing.T) {268 conn := new(mockConn)269 mc := &mysqlConn{270 buf: newBuffer(conn),271 cfg: new(Config),272 sequence: 42,273 closech: make(chan struct{}),274 }275 conn.data = []byte{72, 0, 0, 42, 10, 53, 46, 53, 46, 56, 0, 165, 0, 0, 0,276 60, 70, 63, 58, 68, 104, 34, 97, 0, 223, 247, 33, 2, 0, 15, 128, 21, 0,277 0, 0, 0, 0, 0, 0, 0, 0, 0, 98, 120, 114, 47, 85, 75, 109, 99, 51, 77,278 50, 64, 0, 109, 121, 115, 113, 108, 95, 110, 97, 116, 105, 118, 101, 95,279 112, 97, 115, 115, 119, 111, 114, 100}280 conn.maxReads = 1281 authData, pluginName, err := mc.readHandshakePacket()282 if err != nil {283 t.Fatalf("got error: %v", err)284 }285 if pluginName != "mysql_native_password" {286 t.Errorf("expected plugin name 'mysql_native_password', got '%s'", pluginName)287 }288 expectedAuthData := []byte{60, 70, 63, 58, 68, 104, 34, 97, 98, 120, 114,289 47, 85, 75, 109, 99, 51, 77, 50, 64}290 if !bytes.Equal(authData, expectedAuthData) {291 t.Errorf("expected authData '%v', got '%v'", expectedAuthData, authData)292 }293}...

Full Screen

Full Screen

conn.go

Source:conn.go Github

copy

Full Screen

...59}60func (c *ContextConn) Context() context.Context {61 return c.ctx62}63type WrapReadWriteCloserConn struct {64 io.ReadWriteCloser65 underConn net.Conn66}67func WrapReadWriteCloserToConn(rwc io.ReadWriteCloser, underConn net.Conn) net.Conn {68 return &WrapReadWriteCloserConn{69 ReadWriteCloser: rwc,70 underConn: underConn,71 }72}73func (conn *WrapReadWriteCloserConn) LocalAddr() net.Addr {74 if conn.underConn != nil {75 return conn.underConn.LocalAddr()76 }77 return (*net.TCPAddr)(nil)78}79func (conn *WrapReadWriteCloserConn) RemoteAddr() net.Addr {80 if conn.underConn != nil {81 return conn.underConn.RemoteAddr()82 }83 return (*net.TCPAddr)(nil)84}85func (conn *WrapReadWriteCloserConn) SetDeadline(t time.Time) error {86 if conn.underConn != nil {87 return conn.underConn.SetDeadline(t)88 }89 return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}90}91func (conn *WrapReadWriteCloserConn) SetReadDeadline(t time.Time) error {92 if conn.underConn != nil {93 return conn.underConn.SetReadDeadline(t)94 }95 return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}96}97func (conn *WrapReadWriteCloserConn) SetWriteDeadline(t time.Time) error {98 if conn.underConn != nil {99 return conn.underConn.SetWriteDeadline(t)100 }101 return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}102}103type CloseNotifyConn struct {104 net.Conn105 // 1 means closed106 closeFlag int32107 closeFn func()108}109// closeFn will be only called once110func WrapCloseNotifyConn(c net.Conn, closeFn func()) net.Conn {111 return &CloseNotifyConn{112 Conn: c,113 closeFn: closeFn,114 }115}116func (cc *CloseNotifyConn) Close() (err error) {117 pflag := atomic.SwapInt32(&cc.closeFlag, 1)118 if pflag == 0 {119 err = cc.Close()120 if cc.closeFn != nil {121 cc.closeFn()122 }123 }124 return125}126type StatsConn struct {127 net.Conn128 closed int64 // 1 means closed129 totalRead int64130 totalWrite int64131 statsFunc func(totalRead, totalWrite int64)132}133func WrapStatsConn(conn net.Conn, statsFunc func(total, totalWrite int64)) *StatsConn {134 return &StatsConn{135 Conn: conn,136 statsFunc: statsFunc,137 }138}139func (statsConn *StatsConn) Read(p []byte) (n int, err error) {140 n, err = statsConn.Conn.Read(p)141 statsConn.totalRead += int64(n)142 return143}144func (statsConn *StatsConn) Write(p []byte) (n int, err error) {145 n, err = statsConn.Conn.Write(p)146 statsConn.totalWrite += int64(n)147 return148}149func (statsConn *StatsConn) Close() (err error) {150 old := atomic.SwapInt64(&statsConn.closed, 1)151 if old != 1 {152 err = statsConn.Conn.Close()153 if statsConn.statsFunc != nil {154 statsConn.statsFunc(statsConn.totalRead, statsConn.totalWrite)155 }156 }157 return158}159func ConnectServer(protocol string, addr string) (c net.Conn, err error) {160 switch protocol {161 case "tcp":162 return net.Dial("tcp", addr)163 case "kcp":164 kcpConn, errRet := kcp.DialWithOptions(addr, nil, 10, 3)165 if errRet != nil {166 err = errRet167 return168 }169 kcpConn.SetStreamMode(true)170 kcpConn.SetWriteDelay(true)171 kcpConn.SetNoDelay(1, 20, 2, 1)172 kcpConn.SetWindowSize(128, 512)173 kcpConn.SetMtu(1350)174 kcpConn.SetACKNoDelay(false)175 kcpConn.SetReadBuffer(4194304)176 kcpConn.SetWriteBuffer(4194304)177 c = kcpConn178 return179 default:180 return nil, fmt.Errorf("unsupport protocol: %s", protocol)181 }182}183func ConnectServerByProxy(proxyURL string, protocol string, addr string) (c net.Conn, err error) {184 switch protocol {185 case "tcp":186 return gnet.DialTcpByProxy(proxyURL, addr)187 case "kcp":188 // http proxy is not supported for kcp189 return ConnectServer(protocol, addr)...

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1Go Lang: Custom Package (Part 2)2Go Lang: Custom Package (Part 3)3Go Lang: Custom Package (Part 4)4Go Lang: Custom Package (Part 5)5Go Lang: Custom Package (Part 6)6Go Lang: Custom Package (Part 7)7Go Lang: Custom Package (Part 8)8Go Lang: Custom Package (Part 9)9Go Lang: Custom Package (Part 10)10Go Lang: Custom Package (Part 11)11Go Lang: Custom Package (Part 12)12Go Lang: Custom Package (Part 13)13Go Lang: Custom Package (Part 14)14Go Lang: Custom Package (Part 15)15Go Lang: Custom Package (Part 16)16Go Lang: Custom Package (Part 17)17Go Lang: Custom Package (Part 18)18Go Lang: Custom Package (Part 19)19Go Lang: Custom Package (Part 20)20Go Lang: Custom Package (Part 21)21Go Lang: Custom Package (Part 22)

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful