ch03

package
v0.0.0-...-42e8fca Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 25, 2024 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Page 64 - 65 Listing 3-10: A function that pings a network connection at a regular interval.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Pinger

func Pinger(ctx context.Context, w io.Writer, reset <-chan time.Duration)
Example
ctx, cancel := context.WithCancel(context.Background())
r, w := io.Pipe() // in lieu of net.Conn
done := make(chan struct{})
resetTimer := make(chan time.Duration, 1)
resetTimer <- time.Second // initial ping interval

go func() {
	Pinger(ctx, w, resetTimer)
	close(done)
}()

receivePing := func(d time.Duration, r io.Reader) {
	if d >= 0 {
		fmt.Printf("resetting timer (%s)\n", d)
		resetTimer <- d
	}

	now := time.Now()
	buf := make([]byte, 1024)
	n, err := r.Read(buf)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Printf("received %q (%s)\n", buf[:n], time.Since(now).Round(100*time.Millisecond))
}

for i, v := range []int64{0, 200, 300, 0, -1, -1, -1} {
	fmt.Printf("Run %d: \n", i+1)
	receivePing(time.Duration(v)*time.Millisecond, r)
}

cancel()
<-done // ensures the pinger exits after canceling the context

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL