Skip to content

Commit 5c6c4c6

Browse files
mpilquistmtomko
authored andcommitted
Merge pull request #3591 from mtomko/main
Fix for #3590
1 parent 1887557 commit 5c6c4c6

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

io/jvm/src/main/scala/fs2/io/net/SelectingSocketGroup.scala

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
package fs2
2323
package io.net
2424

25+
import scala.concurrent.duration._
26+
2527
import cats.effect.LiftIO
2628
import cats.effect.Selector
2729
import cats.effect.kernel.Async
@@ -100,7 +102,11 @@ private final class SelectingSocketGroup[F[_]: LiftIO: Dns](selector: Selector)(
100102
): Resource[F, (SocketAddress[IpAddress], Stream[F, Socket[F]])] =
101103
Resource
102104
.make(F.delay(selector.provider.openServerSocketChannel())) { ch =>
103-
F.delay(ch.close())
105+
def waitForDeregistration: F[Unit] =
106+
// sleep time set to be short enough to not noticeably delay shutdown but long enough to
107+
// give the runtime/cpu time to do something else; some guesswork involved here
108+
F.delay(ch.isRegistered()).ifM(F.sleep(2.millis) >> waitForDeregistration, F.unit)
109+
F.delay(ch.close()) >> waitForDeregistration
104110
}
105111
.evalMap { serverCh =>
106112
val configure = address.traverse(_.resolve).flatMap { ip =>

io/shared/src/test/scala/fs2/io/net/tcp/SocketSuite.scala

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,18 @@ class SocketSuite extends Fs2Suite with SocketSuitePlatform {
269269
}
270270
}
271271

272+
test("sockets are released at the end of the resource scope") {
273+
val f =
274+
Network[IO].serverResource(port = Some(port"9071")).use { case (bindAddress, clients) =>
275+
clients.foreach(_ => IO.sleep(1.second)).compile.drain.background.surround {
276+
Network[IO].client(bindAddress).use { client =>
277+
client.read(1).assertEquals(None)
278+
}
279+
}
280+
}
281+
f >> f >> f
282+
}
283+
272284
test("endOfOutput / endOfInput ignores ENOTCONN") {
273285
Network[IO].serverResource().use { case (bindAddress, clients) =>
274286
Network[IO].client(bindAddress).surround(IO.sleep(100.millis)).background.surround {

0 commit comments

Comments
 (0)