@@ -3,8 +3,10 @@ package main
3
3
import (
4
4
"bufio"
5
5
"context"
6
+ "errors"
6
7
"flag"
7
8
"fmt"
9
+ "io"
8
10
"log"
9
11
"net"
10
12
"net/url"
@@ -135,8 +137,9 @@ func main() {
135
137
136
138
deathNote := sync.Map {}
137
139
138
- connectionAccepted := make (chan net.Addr )
139
- connectionLost := make (chan net.Addr )
140
+ // Buffered so we don't block the main process.
141
+ connectionAccepted := make (chan net.Addr , 10 )
142
+ connectionLost := make (chan net.Addr , 10 )
140
143
141
144
go processRequests (& deathNote , connectionAccepted , connectionLost )
142
145
@@ -206,8 +209,10 @@ func processRequests(deathNote *sync.Map, connectionAccepted chan<- net.Addr, co
206
209
}
207
210
208
211
if err != nil {
209
- log .Println (err )
210
- break
212
+ if ! errors .Is (err , io .EOF ) {
213
+ log .Println (err )
214
+ }
215
+ return
211
216
}
212
217
}
213
218
}(conn )
@@ -216,45 +221,28 @@ func processRequests(deathNote *sync.Map, connectionAccepted chan<- net.Addr, co
216
221
217
222
func waitForPruneCondition (ctx context.Context , connectionAccepted <- chan net.Addr , connectionLost <- chan net.Addr ) {
218
223
connectionCount := 0
219
- never := make (chan time.Time , 1 )
220
- defer close (never )
221
-
222
- handleConnectionAccepted := func (addr net.Addr ) {
223
- log .Printf ("New client connected: %s" , addr )
224
- connectionCount ++
225
- }
226
-
227
- select {
228
- case <- time .After (connectionTimeout ):
229
- panic ("Timed out waiting for the first connection" )
230
- case addr := <- connectionAccepted :
231
- handleConnectionAccepted (addr )
232
- case <- ctx .Done ():
233
- log .Println ("Signal received" )
234
- return
235
- }
236
-
224
+ timer := time .NewTimer (connectionTimeout )
237
225
for {
238
- var noConnectionTimeout <- chan time.Time
239
- if connectionCount == 0 {
240
- noConnectionTimeout = time .After (reconnectionTimeout )
241
- } else {
242
- noConnectionTimeout = never
243
- }
244
-
245
226
select {
246
227
case addr := <- connectionAccepted :
247
- handleConnectionAccepted (addr )
248
- break
228
+ log .Printf ("New client connected: %s" , addr )
229
+ connectionCount ++
230
+ if connectionCount == 1 {
231
+ if ! timer .Stop () {
232
+ <- timer .C
233
+ }
234
+ }
249
235
case addr := <- connectionLost :
250
236
log .Printf ("Client disconnected: %s" , addr .String ())
251
237
connectionCount --
252
- break
238
+ if connectionCount == 0 {
239
+ timer .Reset (reconnectionTimeout )
240
+ }
253
241
case <- ctx .Done ():
254
242
log .Println ("Signal received" )
255
243
return
256
- case <- noConnectionTimeout :
257
- log .Println ("Timed out waiting for re- connection" )
244
+ case <- timer . C :
245
+ log .Println ("Timeout waiting for connection" )
258
246
return
259
247
}
260
248
}
0 commit comments