0
# Socket Builders
1
2
Socket builders provide a fluent API for creating and configuring sockets in ktor-network. The builder pattern allows for clean, readable socket creation with optional configuration.
3
4
## Core Builder Functions
5
6
### Primary Entry Point
7
8
```kotlin { .api }
9
fun aSocket(selector: SelectorManager): SocketBuilder
10
```
11
12
Creates the main socket builder that provides access to TCP and UDP socket builders.
13
14
**Parameters:**
15
- `selector: SelectorManager` - The selector manager for I/O event handling
16
17
**Returns:** `SocketBuilder` - Main builder for choosing socket type
18
19
### Main Socket Builder
20
21
```kotlin { .api }
22
class SocketBuilder {
23
fun tcp(): TcpSocketBuilder
24
fun udp(): UDPSocketBuilder
25
}
26
```
27
28
The main builder class that branches into specific socket types.
29
30
## TCP Socket Builder
31
32
```kotlin { .api }
33
class TcpSocketBuilder : Configurable<TcpSocketBuilder, SocketOptions.TCPClientSocketOptions> {
34
suspend fun connect(remoteAddress: SocketAddress): Socket
35
suspend fun bind(localAddress: SocketAddress? = null): ServerSocket
36
fun configure(block: SocketOptions.TCPClientSocketOptions.() -> Unit): TcpSocketBuilder
37
}
38
```
39
40
Builder for creating TCP sockets with client and server capabilities.
41
42
### TCP Client Connection
43
44
```kotlin { .api }
45
suspend fun connect(remoteAddress: SocketAddress): Socket
46
```
47
48
Creates a TCP client socket and connects to the specified remote address.
49
50
**Parameters:**
51
- `remoteAddress: SocketAddress` - The remote address to connect to
52
53
**Returns:** `Socket` - A connected TCP socket ready for I/O operations
54
55
### TCP Server Binding
56
57
```kotlin { .api }
58
suspend fun bind(localAddress: SocketAddress? = null): ServerSocket
59
```
60
61
Creates a TCP server socket bound to the specified local address.
62
63
**Parameters:**
64
- `localAddress: SocketAddress?` - Local address to bind to, or null for any available address
65
66
**Returns:** `ServerSocket` - A server socket ready to accept connections
67
68
## UDP Socket Builder
69
70
```kotlin { .api }
71
class UDPSocketBuilder : Configurable<UDPSocketBuilder, SocketOptions.UDPSocketOptions> {
72
suspend fun bind(localAddress: SocketAddress? = null): BoundDatagramSocket
73
suspend fun connect(remoteAddress: SocketAddress): ConnectedDatagramSocket
74
fun configure(block: SocketOptions.UDPSocketOptions.() -> Unit): UDPSocketBuilder
75
}
76
```
77
78
Builder for creating UDP sockets with bound and connected variants.
79
80
### UDP Bound Socket
81
82
```kotlin { .api }
83
suspend fun bind(localAddress: SocketAddress? = null): BoundDatagramSocket
84
```
85
86
Creates a UDP socket bound to a local address for receiving datagrams from any source.
87
88
**Parameters:**
89
- `localAddress: SocketAddress?` - Local address to bind to, or null for any available address
90
91
**Returns:** `BoundDatagramSocket` - A bound UDP socket for datagram communication
92
93
### UDP Connected Socket
94
95
```kotlin { .api }
96
suspend fun connect(remoteAddress: SocketAddress): ConnectedDatagramSocket
97
```
98
99
Creates a UDP socket connected to a specific remote address for efficient point-to-point communication.
100
101
**Parameters:**
102
- `remoteAddress: SocketAddress` - The remote address to connect to
103
104
**Returns:** `ConnectedDatagramSocket` - A connected UDP socket for efficient datagram exchange
105
106
## Configuration Interface
107
108
```kotlin { .api }
109
interface Configurable<out T : Configurable<T, Options>, Options : SocketOptions> {
110
fun configure(block: Options.() -> Unit): T
111
}
112
```
113
114
Interface enabling fluent configuration of socket builders with type-safe options.
115
116
## Usage Examples
117
118
### Basic TCP Client
119
```kotlin
120
import io.ktor.network.sockets.*
121
import io.ktor.network.selector.*
122
123
suspend fun createTcpClient() {
124
val selectorManager = SelectorManager()
125
val socket = aSocket(selectorManager)
126
.tcp()
127
.connect(InetSocketAddress("example.com", 80))
128
129
// Use socket...
130
socket.close()
131
}
132
```
133
134
### Configured TCP Server
135
```kotlin
136
suspend fun createConfiguredTcpServer() {
137
val selectorManager = SelectorManager()
138
val serverSocket = aSocket(selectorManager)
139
.tcp()
140
.configure {
141
reuseAddress = true
142
reusePort = true
143
backlogSize = 100
144
}
145
.bind(InetSocketAddress("localhost", 8080))
146
147
// Accept connections...
148
serverSocket.close()
149
}
150
```
151
152
### UDP Socket Examples
153
```kotlin
154
// Bound UDP socket for receiving from any source
155
suspend fun createUdpReceiver() {
156
val selectorManager = SelectorManager()
157
val socket = aSocket(selectorManager)
158
.udp()
159
.bind(InetSocketAddress("localhost", 9999))
160
161
val datagram = socket.receive()
162
socket.close()
163
}
164
165
// Connected UDP socket for efficient point-to-point
166
suspend fun createUdpSender() {
167
val selectorManager = SelectorManager()
168
val socket = aSocket(selectorManager)
169
.udp()
170
.configure {
171
broadcast = false
172
}
173
.connect(InetSocketAddress("target.com", 8888))
174
175
// Send datagrams efficiently...
176
socket.close()
177
}
178
```
179
180
### Advanced TCP Configuration
181
```kotlin
182
suspend fun createOptimizedTcpConnection() {
183
val selectorManager = SelectorManager()
184
val socket = aSocket(selectorManager)
185
.tcp()
186
.configure {
187
noDelay = true // Disable Nagle's algorithm
188
keepAlive = true // Enable TCP keepalive
189
socketTimeout = 30000 // 30 second timeout
190
reuseAddress = true // Allow address reuse
191
sendBufferSize = 64 * 1024 // 64KB send buffer
192
receiveBufferSize = 64 * 1024 // 64KB receive buffer
193
}
194
.connect(InetSocketAddress("api.example.com", 443))
195
196
// High-performance connection ready
197
socket.close()
198
}
199
```
200
201
## Type Definitions
202
203
### Required Import Statements
204
205
```kotlin
206
import io.ktor.network.sockets.*
207
import io.ktor.network.selector.SelectorManager
208
import io.ktor.utils.io.*
209
import kotlinx.coroutines.*
210
```
211
212
### Related Types
213
214
- `SelectorManager` - See [Selectors](./selectors.md)
215
- `SocketAddress`, `InetSocketAddress` - See [Address Types](./address-types.md)
216
- `SocketOptions.*` - See [Socket Options](./socket-options.md)
217
- `Socket`, `ServerSocket` - See [Socket Interfaces](./socket-interfaces.md)
218
- `BoundDatagramSocket`, `ConnectedDatagramSocket` - See [Datagram Sockets](./datagram-sockets.md)