Skip to content

Commit

Permalink
protocol: reset timeout after processing header
Browse files Browse the repository at this point in the history
Fixes #75

Signed-off-by: Pires <pjpires@gmail.com>
  • Loading branch information
pires committed Jul 13, 2021
1 parent 73e795e commit 37fda36
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
4 changes: 4 additions & 0 deletions protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ func (p *Listener) Accept() (net.Conn, error) {
}

if d := p.ReadHeaderTimeout; d != 0 {
// The deadline will be reset after parsing the header.
// Otherwise, future p.conn.Read() will timeout.
conn.SetReadDeadline(time.Now().Add(d))
}

Expand Down Expand Up @@ -106,10 +108,12 @@ func NewConn(conn net.Conn, opts ...func(*Conn)) *Conn {
func (p *Conn) Read(b []byte) (int, error) {
p.once.Do(func() {
p.readErr = p.readHeader()
p.conn.SetReadDeadline(time.Time{})
})
if p.readErr != nil {
return 0, p.readErr
}

return p.bufReader.Read(b)
}

Expand Down
6 changes: 3 additions & 3 deletions protocol_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func TestPassthrough(t *testing.T) {
conn, err := net.Dial("tcp", pl.Addr().String())
if err != nil {
t.Fatalf("err: %v", err)
}
}
defer conn.Close()

conn.Write([]byte("ping"))
Expand Down Expand Up @@ -99,7 +99,7 @@ func TestReadHeaderTimeout(t *testing.T) {
recv := make([]byte, 4)
_, err = conn.Read(recv)

if err != nil && !errors.Is(err, os.ErrDeadlineExceeded){
if err != nil && !errors.Is(err, os.ErrDeadlineExceeded) {
t.Fatal("should timeout")
}
}
Expand All @@ -113,7 +113,7 @@ func TestReadHeaderTimeoutIsReset(t *testing.T) {
}

pl := &Listener{
Listener: l,
Listener: l,
ReadHeaderTimeout: timeout,
}

Expand Down

0 comments on commit 37fda36

Please sign in to comment.