0
# TCP Operations
1
2
TCP client and server socket operations with support for connection establishment, data transmission, and server socket binding.
3
4
## Capabilities
5
6
### TCP Socket Builder
7
8
Builder for creating TCP client and server sockets with comprehensive configuration options.
9
10
```kotlin { .api }
11
/**
12
* TCP socket builder
13
*/
14
class TcpSocketBuilder : Configurable<TcpSocketBuilder, SocketOptions.PeerSocketOptions> {
15
/**
16
* Connect to hostname and port
17
* @param hostname Target hostname to connect to
18
* @param port Target port number
19
* @param configure Configuration block for TCP client options
20
* @returns Connected Socket instance
21
*/
22
suspend fun connect(
23
hostname: String,
24
port: Int,
25
configure: SocketOptions.TCPClientSocketOptions.() -> Unit = {}
26
): Socket
27
28
/**
29
* Connect to remote address
30
* @param remoteAddress Target socket address
31
* @param configure Configuration block for TCP client options
32
* @returns Connected Socket instance
33
*/
34
suspend fun connect(
35
remoteAddress: SocketAddress,
36
configure: SocketOptions.TCPClientSocketOptions.() -> Unit = {}
37
): Socket
38
39
/**
40
* Bind server socket at port to listen to hostname
41
* @param hostname Local hostname to bind to (default: "0.0.0.0")
42
* @param port Local port to bind to (default: 0 for auto-assignment)
43
* @param configure Configuration block for acceptor options
44
* @returns ServerSocket instance ready to accept connections
45
*/
46
suspend fun bind(
47
hostname: String = "0.0.0.0",
48
port: Int = 0,
49
configure: SocketOptions.AcceptorOptions.() -> Unit = {}
50
): ServerSocket
51
52
/**
53
* Bind server socket to listen to local address
54
* @param localAddress Local socket address to bind to (null for any address)
55
* @param configure Configuration block for acceptor options
56
* @returns ServerSocket instance ready to accept connections
57
*/
58
suspend fun bind(
59
localAddress: SocketAddress? = null,
60
configure: SocketOptions.AcceptorOptions.() -> Unit = {}
61
): ServerSocket
62
}
63
```
64
65
**Usage Examples:**
66
67
```kotlin
68
import io.ktor.network.sockets.*
69
import io.ktor.network.selector.*
70
import kotlinx.coroutines.*
71
72
val selectorManager = SelectorManager()
73
74
// TCP Client - Connect to server
75
val clientSocket = aSocket(selectorManager).tcp().connect("localhost", 8080) {
76
noDelay = true
77
keepAlive = true
78
socketTimeout = 30000 // 30 seconds
79
}
80
81
// TCP Server - Bind and listen
82
val serverSocket = aSocket(selectorManager).tcp().bind("0.0.0.0", 8080) {
83
backlogSize = 50
84
reuseAddress = true
85
}
86
87
// Accept connections
88
while (true) {
89
val client = serverSocket.accept()
90
launch {
91
// Handle client connection
92
val connection = client.connection()
93
val request = connection.input.readUTF8Line()
94
connection.output.writeStringUtf8("Echo: $request")
95
connection.output.flush()
96
client.close()
97
}
98
}
99
```
100
101
### Connected Socket Interface
102
103
Interface representing a connected TCP socket with read/write capabilities.
104
105
```kotlin { .api }
106
/**
107
* Represents a connected socket
108
*/
109
interface Socket : ReadWriteSocket, ABoundSocket, AConnectedSocket, CoroutineScope
110
111
/**
112
* Represents both readable and writable socket
113
*/
114
interface ReadWriteSocket : ASocket, AReadable, AWritable
115
```
116
117
### Server Socket Interface
118
119
Interface for TCP server sockets that can accept incoming connections.
120
121
```kotlin { .api }
122
/**
123
* Represents a server-bound socket ready for accepting connections
124
*/
125
interface ServerSocket : ASocket, ABoundSocket, Acceptable<Socket>
126
127
/**
128
* Represents a socket source, for example server socket
129
*/
130
interface Acceptable<out S : ASocket> : ASocket {
131
/**
132
* Suspends until a connection is available and returns it or throws if something goes wrong
133
* @returns accepted socket
134
* @throws IOException
135
*/
136
suspend fun accept(): S
137
}
138
139
/** The port number of the current server */
140
val ServerSocket.port: Int
141
```
142
143
**Usage Example:**
144
145
```kotlin
146
import io.ktor.network.sockets.*
147
import io.ktor.network.selector.*
148
import kotlinx.coroutines.*
149
150
val selectorManager = SelectorManager()
151
152
// Create server socket
153
val serverSocket = aSocket(selectorManager).tcp().bind("localhost", 8080)
154
println("Server listening on port ${serverSocket.port}")
155
156
// Accept and handle connections
157
while (true) {
158
val clientSocket = serverSocket.accept()
159
println("Client connected from: ${clientSocket.remoteAddress}")
160
161
launch {
162
try {
163
val connection = clientSocket.connection()
164
165
// Read from client
166
val message = connection.input.readUTF8Line()
167
println("Received: $message")
168
169
// Write to client
170
connection.output.writeStringUtf8("Server received: $message")
171
connection.output.flush()
172
173
} catch (e: Exception) {
174
println("Error handling client: ${e.message}")
175
} finally {
176
clientSocket.close()
177
}
178
}
179
}
180
```
181
182
### Socket I/O Interfaces
183
184
Interfaces for reading and writing data to TCP sockets.
185
186
```kotlin { .api }
187
/**
188
* Represents a readable socket
189
*/
190
interface AReadable {
191
/**
192
* Attach channel for reading so incoming bytes appears in the attached channel
193
* Only one channel could be attached
194
* @param channel ByteChannel to attach for reading
195
* @returns a job that does supply data
196
*/
197
fun attachForReading(channel: ByteChannel): WriterJob
198
}
199
200
/**
201
* Represents a writable socket
202
*/
203
interface AWritable {
204
/**
205
* Attach channel for writing so bytes written to the attached channel will be transmitted
206
* Only one channel could be attached
207
* @param channel ByteChannel to attach for writing
208
* @returns a job that does transmit data from the channel
209
*/
210
fun attachForWriting(channel: ByteChannel): ReaderJob
211
}
212
213
/** Open a read channel, could be done only once */
214
fun AReadable.openReadChannel(): ByteReadChannel
215
216
/**
217
* Open a write channel, could be opened only once
218
* @param autoFlush whether returned channel do flush for every write operation
219
*/
220
fun AWritable.openWriteChannel(autoFlush: Boolean = false): ByteWriteChannel
221
```
222
223
### Connection Wrapper
224
225
Convenience class that wraps a socket with its input and output channels.
226
227
```kotlin { .api }
228
/**
229
* Represents a connected socket with its input and output
230
*/
231
class Connection(
232
val socket: Socket,
233
val input: ByteReadChannel,
234
val output: ByteWriteChannel
235
)
236
237
/** Opens socket input and output channels and returns connection object */
238
fun Socket.connection(): Connection
239
```
240
241
**Usage Example:**
242
243
```kotlin
244
import io.ktor.network.sockets.*
245
import io.ktor.network.selector.*
246
247
val selectorManager = SelectorManager()
248
249
// Connect to server
250
val socket = aSocket(selectorManager).tcp().connect("localhost", 8080)
251
252
// Get connection with I/O channels
253
val connection = socket.connection()
254
255
// Write data
256
connection.output.writeStringUtf8("Hello, Server!")
257
connection.output.flush()
258
259
// Read response
260
val response = connection.input.readUTF8Line()
261
println("Server response: $response")
262
263
// Alternative: Use raw socket I/O
264
val readChannel = socket.openReadChannel()
265
val writeChannel = socket.openWriteChannel(autoFlush = true)
266
267
writeChannel.writeStringUtf8("Another message")
268
val anotherResponse = readChannel.readUTF8Line()
269
270
// Clean up
271
socket.close()
272
selectorManager.close()
273
```