Scoop API

scoop:scoop.asyncio:0.1.0

src/tcp_listener.scoop

Selected production source · src/tcp_listener.scoop

1package scoop.asyncio
3import scoop.platform.net.SocketAddress
5/**
6 * An owned TCP listening socket associated with one event loop.
7 */
8public interface AsyncTcpListener: AsyncCloseable {
9 /**
10 * The actual bound address, including a kernel-selected ephemeral port.
11 */
12 public val localAddress: SocketAddress
13 /**
14 * Suspends until a connection is accepted and returns a separately owned TCP stream.
15 */
16 public suspend fun accept(): AsyncTcpStream
19internal class TcpListener(
20 private val owner: OwnedEndpoint,
21 public override val localAddress: SocketAddress
22): AsyncTcpListener {
23 public override suspend fun accept(): AsyncTcpStream {
24 val job = owner.loop.requireJob()
25 val reservation = owner.reserve(false)
26 try {
27 val target = owner.loop.connectionOwner()
28 return suspendCoroutine<AsyncTcpStream> {
29 continuation ->
30 val operation =
31 CallbackOperation(
32 owner.loop,
33 owner.loop.nextOperation(),
34 {
35 _,
36 id -> @Unsafe
37 {
38 return@CallbackOperation nativeStatus(
39 id,
40 nativeTcpAccept(owner.pointer, target.nativePointer(), id)
41 )
42 }
43 },
44 {
45 _,
46 id -> @Unsafe
47 {
48 nativeTcpAcceptCancel(owner.pointer, id)
49 }
50 },
51 {
52 event,
53 selected -> target.post {
54 finishEndpointCreation<AsyncTcpStream>(
55 target,
56 EndpointKind.Tcp,
57 event.result,
58 selected,
59 continuation,
60 {
61 accepted -> TcpStream(
62 accepted,
63 tcpAddress(accepted.pointer, false),
64 tcpAddress(accepted.pointer, true)
65 )
66 }
67 )
68 }
69 }
70 )
71 operation.subscribe(job)
72 owner.attach(operation, false)
73 owner.loop.submit(operation)
74 }
75 } finally {
76 reservation.dispose()
77 }
78 }
80 public override suspend fun close() {
81 owner.close()
82 }