0
# Ktor Network
1
2
Ktor Network provides comprehensive asynchronous networking capabilities for Kotlin Multiplatform applications targeting macOS ARM64. Built on Kotlin coroutines, it offers socket abstractions, connection management, and low-level I/O operations with platform-specific optimizations.
3
4
## Package Information
5
6
- **Package Name**: io.ktor:ktor-network-macosarm64
7
- **Package Type**: Maven/Gradle
8
- **Language**: Kotlin (Multiplatform)
9
- **Platform Target**: macOS ARM64
10
- **Installation**: `implementation("io.ktor:ktor-network-macosarm64:3.2.0")`
11
12
## Core Imports
13
14
```kotlin
15
import io.ktor.network.sockets.*
16
import io.ktor.network.selector.*
17
```
18
19
For UDP/Datagram operations:
20
```kotlin
21
import io.ktor.network.sockets.Datagram
22
import io.ktor.network.sockets.BoundDatagramSocket
23
import io.ktor.network.sockets.ConnectedDatagramSocket
24
```
25
26
For socket configuration:
27
```kotlin
28
import io.ktor.network.sockets.SocketOptions
29
import io.ktor.network.sockets.TypeOfService
30
```
31
32
## Basic Usage
33
34
### TCP Client Socket
35
```kotlin
36
import io.ktor.network.sockets.*
37
import io.ktor.network.selector.*
38
import kotlinx.coroutines.*
39
40
suspend fun connectTcp() {
41
val selectorManager = SelectorManager(Dispatchers.IO)
42
val socket = aSocket(selectorManager).tcp().connect(InetSocketAddress("example.com", 80))
43
44
// Use socket for communication
45
val input = socket.openReadChannel()
46
val output = socket.openWriteChannel(autoFlush = true)
47
48
// Clean up
49
socket.close()
50
selectorManager.close()
51
}
52
```
53
54
### TCP Server Socket
55
```kotlin
56
suspend fun startTcpServer() {
57
val selectorManager = SelectorManager(Dispatchers.IO)
58
val serverSocket = aSocket(selectorManager).tcp().bind(InetSocketAddress("localhost", 8080))
59
60
while (true) {
61
val clientSocket = serverSocket.accept()
62
launch {
63
// Handle client connection
64
val input = clientSocket.openReadChannel()
65
val output = clientSocket.openWriteChannel(autoFlush = true)
66
// ... handle communication ...
67
clientSocket.close()
68
}
69
}
70
}
71
```
72
73
### UDP Socket
74
```kotlin
75
suspend fun sendUdpMessage() {
76
val selectorManager = SelectorManager(Dispatchers.IO)
77
val socket = aSocket(selectorManager).udp().bind()
78
79
val message = "Hello UDP"
80
val datagram = Datagram(
81
packet = ByteReadPacket(message.toByteArray()),
82
address = InetSocketAddress("localhost", 9999)
83
)
84
85
socket.send(datagram)
86
socket.close()
87
selectorManager.close()
88
}
89
```
90
91
## Architecture
92
93
Ktor Network is built around several core concepts:
94
95
- **Socket Builders**: Fluent API for creating sockets with `aSocket(selector).tcp()` or `aSocket(selector).udp()`
96
- **Socket Types**: Different interfaces for different socket capabilities (readable, writable, bound, connected)
97
- **Selector Manager**: Platform-specific I/O event management using coroutines
98
- **Address System**: Unified addressing for Internet and Unix domain sockets
99
- **Options System**: Comprehensive socket configuration for performance and behavior tuning
100
101
## Capabilities
102
103
### Socket Creation and Builders
104
105
Primary entry points and builder pattern for socket creation with TCP and UDP support.
106
107
```kotlin { .api }
108
fun aSocket(selector: SelectorManager): SocketBuilder
109
110
class SocketBuilder {
111
fun tcp(): TcpSocketBuilder
112
fun udp(): UDPSocketBuilder
113
}
114
115
class TcpSocketBuilder : Configurable<TcpSocketBuilder, SocketOptions.TCPClientSocketOptions> {
116
suspend fun connect(remoteAddress: SocketAddress): Socket
117
suspend fun bind(localAddress: SocketAddress? = null): ServerSocket
118
fun configure(block: SocketOptions.TCPClientSocketOptions.() -> Unit): TcpSocketBuilder
119
}
120
121
class UDPSocketBuilder : Configurable<UDPSocketBuilder, SocketOptions.UDPSocketOptions> {
122
suspend fun bind(localAddress: SocketAddress? = null): BoundDatagramSocket
123
suspend fun connect(remoteAddress: SocketAddress): ConnectedDatagramSocket
124
fun configure(block: SocketOptions.UDPSocketOptions.() -> Unit): UDPSocketBuilder
125
}
126
```
127
128
[Socket Builders](./socket-builders.md)
129
130
### Core Socket Interfaces and Types
131
132
Complete socket interface hierarchy with base types and capability interfaces for different socket behaviors.
133
134
```kotlin { .api }
135
interface ASocket : Closeable, DisposableHandle {
136
val socketContext: Job
137
val isClosed: Boolean
138
suspend fun awaitClosed()
139
}
140
141
interface ReadWriteSocket : ASocket, AReadable, AWritable
142
143
interface Socket : ReadWriteSocket, ABoundSocket, AConnectedSocket, CoroutineScope
144
145
interface ServerSocket : ASocket, ABoundSocket, Acceptable<Socket>
146
147
interface AReadable {
148
fun attachForReading(channel: ByteChannel): WriterJob
149
fun openReadChannel(): ByteReadChannel
150
}
151
152
interface AWritable {
153
fun attachForWriting(channel: ByteChannel): ReaderJob
154
fun openWriteChannel(autoFlush: Boolean = false): ByteWriteChannel
155
}
156
```
157
158
[Socket Interfaces](./socket-interfaces.md)
159
160
### UDP/Datagram Socket Functionality
161
162
Specialized UDP socket support with datagram packet handling and both bound and connected socket types.
163
164
```kotlin { .api }
165
class Datagram(val packet: Source, val address: SocketAddress)
166
167
interface BoundDatagramSocket : ASocket, ABoundSocket, DatagramReadWriteChannel
168
169
interface ConnectedDatagramSocket : ASocket, ABoundSocket, AConnectedSocket, DatagramReadWriteChannel
170
171
interface DatagramReadWriteChannel : DatagramReadChannel, DatagramWriteChannel {
172
suspend fun send(datagram: Datagram)
173
suspend fun receive(): Datagram
174
}
175
```
176
177
[Datagram Sockets](./datagram-sockets.md)
178
179
### Socket Address Types and Utilities
180
181
Comprehensive addressing system supporting both Internet and Unix domain sockets.
182
183
```kotlin { .api }
184
sealed class SocketAddress
185
186
data class InetSocketAddress(val hostname: String, val port: Int) : SocketAddress
187
188
data class UnixSocketAddress(val path: String) : SocketAddress
189
190
fun SocketAddress.port(): Int // Extension for InetSocketAddress only
191
```
192
193
[Address Types](./address-types.md)
194
195
### Socket Configuration and Options
196
197
Extensive configuration system for tuning socket behavior, performance, and network properties.
198
199
```kotlin { .api }
200
sealed class SocketOptions
201
202
class SocketOptions.TCPClientSocketOptions : SocketOptions.PeerSocketOptions() {
203
var keepAlive: Boolean?
204
var noDelay: Boolean?
205
var lingerSeconds: Int?
206
var socketTimeout: Long?
207
}
208
209
class SocketOptions.UDPSocketOptions : SocketOptions.PeerSocketOptions() {
210
var broadcast: Boolean?
211
}
212
213
class SocketOptions.AcceptorOptions : SocketOptions() {
214
var backlogSize: Int
215
var reuseAddress: Boolean
216
var reusePort: Boolean
217
}
218
```
219
220
[Socket Options](./socket-options.md)
221
222
### Selector and Event Management
223
224
Platform-specific I/O event management system built on coroutines for efficient async operations.
225
226
```kotlin { .api }
227
interface SelectorManager : Closeable {
228
val coroutineContext: CoroutineContext
229
fun notifyClosed(selectable: Selectable)
230
suspend fun select(selectable: Selectable, interest: SelectInterest)
231
}
232
233
fun SelectorManager(dispatcher: CoroutineContext = Dispatchers.IO): SelectorManager
234
235
enum class SelectInterest { READ, WRITE, ACCEPT, CONNECT }
236
```
237
238
[Selectors](./selectors.md)
239
240
### Utility Functions and Extensions
241
242
Convenience functions, extensions, and helper utilities for common socket operations and type conversions.
243
244
```kotlin { .api }
245
fun Socket.connection(): Connection
246
247
val ServerSocket.port: Int
248
249
suspend fun ASocket.awaitClosed()
250
251
class Connection(val socket: Socket, val input: ByteReadChannel, val output: ByteWriteChannel) : Closeable
252
253
value class TypeOfService(val value: UByte) {
254
constructor(value: Int) : this(value.toUByte())
255
256
val intValue: Int get() = value.toInt()
257
258
companion object {
259
val UNDEFINED: TypeOfService
260
val IPTOS_LOWCOST: TypeOfService
261
val IPTOS_RELIABILITY: TypeOfService
262
val IPTOS_THROUGHPUT: TypeOfService
263
val IPTOS_LOWDELAY: TypeOfService
264
}
265
}
266
```
267
268
[Utilities](./utilities.md)
269
270
## Exception Types
271
272
```kotlin { .api }
273
class SocketTimeoutException(message: String) : Exception
274
```