Skip to content

Commit bb72151

Browse files
authored
Merge pull request goburrow#36 from grid-x/wz2b-master
fix: flush read buffer before writing request
2 parents ab35ea4 + fd3dfbb commit bb72151

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

tcpclient.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,15 @@ func (mb *tcpTransporter) Send(aduRequest []byte) (aduResponse []byte, err error
155155
return
156156
}
157157

158+
// If an answer to a previously timed-out request is already in teh buffer, this will result
159+
// in a transaction ID mismatch from which we will never recover. To prevent this, just
160+
// flush any previous reponses before launching the next poll. That's throwing away
161+
// possibly useful data, but the previous request was already satisfied with a timeout
162+
// error so that probably makes the most sense here.
163+
164+
// Be aware that this call resets the read deadline.
165+
mb.flushAll()
166+
158167
// Set timer to close when idle
159168
mb.lastActivity = time.Now()
160169
mb.startCloseTimer()
@@ -332,3 +341,27 @@ func (mb *tcpTransporter) closeIdle() {
332341
mb.close()
333342
}
334343
}
344+
345+
// flushAll implements a non-blocking read flush. Be warned it resets
346+
// the read deadline.
347+
func (mb *tcpTransporter) flushAll() (int, error) {
348+
if err := mb.conn.SetReadDeadline(time.Now()); err != nil {
349+
return 0, err
350+
}
351+
352+
count := 0
353+
buffer := make([]byte, 1024)
354+
355+
for {
356+
n, err := mb.conn.Read(buffer)
357+
358+
if err != nil {
359+
return count + n, err
360+
} else if n > 0 {
361+
count = count + n
362+
} else {
363+
// didn't flush any new bytes, return
364+
return count, err
365+
}
366+
}
367+
}

0 commit comments

Comments
 (0)