0
# UDP Operations
1
2
UDP datagram socket operations supporting both bound and connected datagram sockets with packet-based communication.
3
4
## Capabilities
5
6
### UDP Socket Builder
7
8
Builder for creating UDP sockets supporting both bound and connected datagram sockets.
9
10
```kotlin { .api }
11
/**
12
* UDP socket builder
13
*/
14
class UDPSocketBuilder : Configurable<UDPSocketBuilder, SocketOptions.UDPSocketOptions> {
15
/**
16
* Bind server socket to listen to local address
17
* @param localAddress Local socket address to bind to (null for any address)
18
* @param configure Configuration block for UDP options
19
* @returns BoundDatagramSocket instance for sending/receiving datagrams
20
*/
21
suspend fun bind(
22
localAddress: SocketAddress? = null,
23
configure: SocketOptions.UDPSocketOptions.() -> Unit = {}
24
): BoundDatagramSocket
25
26
/**
27
* Bind server socket at port to listen to hostname
28
* @param hostname Local hostname to bind to (default: "0.0.0.0")
29
* @param port Local port to bind to (default: 0 for auto-assignment)
30
* @param configure Configuration block for UDP options
31
* @returns BoundDatagramSocket instance for sending/receiving datagrams
32
*/
33
suspend fun bind(
34
hostname: String = "0.0.0.0",
35
port: Int = 0,
36
configure: SocketOptions.UDPSocketOptions.() -> Unit = {}
37
): BoundDatagramSocket
38
39
/**
40
* Create a datagram socket to listen datagrams at local address and set to remote address
41
* @param remoteAddress Remote socket address to connect to
42
* @param localAddress Local socket address to bind to (null for any address)
43
* @param configure Configuration block for UDP options
44
* @returns ConnectedDatagramSocket instance for sending/receiving datagrams to/from specific remote address
45
*/
46
suspend fun connect(
47
remoteAddress: SocketAddress,
48
localAddress: SocketAddress? = null,
49
configure: SocketOptions.UDPSocketOptions.() -> Unit = {}
50
): ConnectedDatagramSocket
51
}
52
```
53
54
**Usage Examples:**
55
56
```kotlin
57
import io.ktor.network.sockets.*
58
import io.ktor.network.selector.*
59
import kotlinx.io.*
60
61
val selectorManager = SelectorManager()
62
63
// UDP Server - Bind to receive datagrams from any source
64
val udpServer = aSocket(selectorManager).udp().bind("0.0.0.0", 8080) {
65
broadcast = true
66
reuseAddress = true
67
}
68
69
// UDP Client - Connect to specific remote address
70
val udpClient = aSocket(selectorManager).udp().connect(
71
remoteAddress = InetSocketAddress("localhost", 8080)
72
) {
73
broadcast = false
74
}
75
76
// Send datagram from bound socket
77
val buffer = Buffer().apply { writeString("Hello UDP Server!") }
78
val datagram = Datagram(buffer, InetSocketAddress("localhost", 8080))
79
udpServer.send(datagram)
80
81
// Receive datagram
82
val receivedDatagram = udpServer.receive()
83
println("Received from ${receivedDatagram.address}: ${receivedDatagram.packet.readText()}")
84
```
85
86
### Datagram Data Structure
87
88
Data structure representing a UDP datagram with packet content and target address.
89
90
```kotlin { .api }
91
/**
92
* UDP datagram with packet content targeted to address
93
* @property packet content as Source
94
* @property address to send to
95
*/
96
class Datagram(
97
val packet: Source,
98
val address: SocketAddress
99
)
100
```
101
102
**Usage Example:**
103
104
```kotlin
105
import io.ktor.network.sockets.*
106
import kotlinx.io.*
107
108
// Create datagram with string content
109
val content = Buffer().apply { writeString("Hello, World!") }
110
val targetAddress = InetSocketAddress("192.168.1.100", 8080)
111
val datagram = Datagram(content, targetAddress)
112
113
// Read packet content
114
val receivedText = datagram.packet.readText()
115
println("Content: $receivedText")
116
println("Target: ${datagram.address}")
117
```
118
119
### Bound Datagram Socket
120
121
Interface for bound UDP sockets that can send and receive datagrams to/from any address.
122
123
```kotlin { .api }
124
/**
125
* Represents a bound datagram socket
126
*/
127
interface BoundDatagramSocket : ASocket, ABoundSocket, DatagramReadWriteChannel
128
```
129
130
### Connected Datagram Socket
131
132
Interface for connected UDP sockets that send and receive datagrams to/from a specific remote address.
133
134
```kotlin { .api }
135
/**
136
* Represents a connected datagram socket
137
*/
138
interface ConnectedDatagramSocket : ASocket, ABoundSocket, AConnectedSocket, DatagramReadWriteChannel
139
```
140
141
### Datagram I/O Channels
142
143
Interfaces for sending and receiving datagrams using channel-based operations.
144
145
```kotlin { .api }
146
/**
147
* A channel for receiving datagrams
148
*/
149
interface DatagramReadChannel {
150
/** Incoming datagrams channel */
151
val incoming: ReceiveChannel<Datagram>
152
153
/** Receive a datagram */
154
suspend fun receive(): Datagram
155
}
156
157
/**
158
* A channel for sending datagrams
159
*/
160
interface DatagramWriteChannel {
161
/** Datagram outgoing channel */
162
val outgoing: SendChannel<Datagram>
163
164
/** Send datagram */
165
suspend fun send(datagram: Datagram)
166
}
167
168
/**
169
* A channel for sending and receiving datagrams
170
*/
171
interface DatagramReadWriteChannel : DatagramReadChannel, DatagramWriteChannel
172
```
173
174
**Usage Examples:**
175
176
```kotlin
177
import io.ktor.network.sockets.*
178
import io.ktor.network.selector.*
179
import kotlinx.coroutines.*
180
import kotlinx.io.*
181
182
val selectorManager = SelectorManager()
183
184
// UDP Echo Server Example
185
suspend fun udpEchoServer() {
186
val server = aSocket(selectorManager).udp().bind("0.0.0.0", 8080)
187
println("UDP server listening on port 8080")
188
189
while (true) {
190
val receivedDatagram = server.receive()
191
println("Received from ${receivedDatagram.address}")
192
193
// Echo back the message
194
val echoContent = Buffer().apply {
195
writeString("Echo: ${receivedDatagram.packet.readText()}")
196
}
197
val echoDatagram = Datagram(echoContent, receivedDatagram.address)
198
server.send(echoDatagram)
199
}
200
}
201
202
// UDP Client Example
203
suspend fun udpClient() {
204
val client = aSocket(selectorManager).udp().connect(
205
InetSocketAddress("localhost", 8080)
206
)
207
208
// Send message
209
val message = Buffer().apply { writeString("Hello Server!") }
210
val datagram = Datagram(message, client.remoteAddress)
211
client.send(datagram)
212
213
// Receive response
214
val response = client.receive()
215
println("Server response: ${response.packet.readText()}")
216
217
client.close()
218
}
219
220
// Using channel-based operations
221
suspend fun channelBasedUdp() {
222
val socket = aSocket(selectorManager).udp().bind()
223
224
// Send using outgoing channel
225
launch {
226
val message = Buffer().apply { writeString("Channel message") }
227
val datagram = Datagram(message, InetSocketAddress("localhost", 8080))
228
socket.outgoing.send(datagram)
229
}
230
231
// Receive using incoming channel
232
launch {
233
for (datagram in socket.incoming) {
234
println("Received: ${datagram.packet.readText()}")
235
}
236
}
237
}
238
```
239
240
## Constants
241
242
```kotlin { .api }
243
/** Maximum UDP datagram size */
244
internal const val MAX_DATAGRAM_SIZE = 65535
245
```