Scoop API

scoop:scoop.asyncio:0.1.0

src/udp.scoop

Selected production source · src/udp.scoop

1package scoop.asyncio
3import scoop.platform.memory.NativeByteBuffer
4import scoop.platform.net.*
6/**
7 * An owned datagram socket preserving message boundaries; each receive describes one datagram.
8 */
9public interface AsyncUdpSocket: AsyncCloseable {
10 /**
11 * The actual bound UDP endpoint.
12 */
13 public val localAddress: SocketAddress
14 /**
15 * Sends one datagram from count readable buffer bytes to the destination.
16 */
17 public suspend fun sendTo(
18 buffer: NativeByteBuffer,
19 destination: SocketAddress,
20 count: Long
21 ): Long
22 /**
23 * Receives one datagram into at most count writable bytes and reports its source and
24 * truncation status.
25 */
26 public suspend fun receiveFrom(buffer: NativeByteBuffer, count: Long): Datagram
29internal class UdpSocket(
30 private val owner: OwnedEndpoint,
31 public override val localAddress: SocketAddress
32): AsyncUdpSocket {
33 public override suspend fun sendTo(
34 buffer: NativeByteBuffer,
35 destination: SocketAddress,
36 count: Long
37 ): Long = sendUdp(owner, buffer, destination, count)
38 public override suspend fun receiveFrom(buffer: NativeByteBuffer, count: Long): Datagram =
39 receiveUdp(owner, buffer, count)
40 public override suspend fun close() {
41 owner.close()
42 }
45internal suspend fun bindUdpOnLoop(
46 loop: LoopOwner,
47 address: SocketAddress,
48 reuse: Boolean
49): AsyncUdpSocket {
50 val job = loop.requireJob()
51 val target = ioAddress(address)
52 return suspendCoroutine<AsyncUdpSocket> {
53 continuation ->
54 val operation =
55 CallbackOperation(
56 loop,
57 loop.nextOperation(),
58 {
59 native,
60 id -> @Unsafe
61 {
62 return@CallbackOperation nativeStatus(
63 id,
64 nativeUdpBind(native, id, target, reuse)
65 )
66 }
67 },
68 { _, _ -> },
69 {
70 event,
71 selected -> finishEndpointCreation<AsyncUdpSocket>(
72 loop,
73 EndpointKind.Udp,
74 event.result,
75 selected,
76 continuation,
77 { owner -> UdpSocket(owner, udpAddress(owner.pointer)) }
78 )
79 }
80 )
81 operation.subscribe(job)
82 loop.submit(operation)
83 }