func (p *PingService) PingHandler(s inet.Stream) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() buf := make([]byte, PingSize) timer := time.NewTimer(pingTimeout) defer timer.Stop() go func() { select { case <-timer.C: case <-ctx.Done(): } s.Close() }() for { _, err := io.ReadFull(s, buf) if err != nil { log.Debug(err) return } _, err = s.Write(buf) if err != nil { log.Debug(err) return } timer.Reset(pingTimeout) } }
// doEcho reads some data from a stream, writes it back and closes the // stream. func doEcho(s inet.Stream) { buf := make([]byte, 1024) n, err := s.Read(buf) if err != nil { log.Println(err) return } log.Printf("read request: %q\n", buf[:n]) _, err = s.Write(buf[:n]) if err != nil { log.Println(err) return } }
func ping(s inet.Stream) (time.Duration, error) { buf := make([]byte, PingSize) u.NewTimeSeededRand().Read(buf) before := time.Now() _, err := s.Write(buf) if err != nil { return 0, err } rbuf := make([]byte, PingSize) _, err = io.ReadFull(s, rbuf) if err != nil { return 0, err } if !bytes.Equal(buf, rbuf) { return 0, errors.New("ping packet was incorrect!") } return time.Since(before), nil }