Ktor network utilities - tvOS x64 target implementation of asynchronous TCP/UDP sockets and related networking functionality for the Ktor framework
—
TCP client and server socket operations with support for connection establishment, data transmission, and server socket binding.
Builder for creating TCP client and server sockets with comprehensive configuration options.
/**
* TCP socket builder
*/
class TcpSocketBuilder : Configurable<TcpSocketBuilder, SocketOptions.PeerSocketOptions> {
/**
* Connect to hostname and port
* @param hostname Target hostname to connect to
* @param port Target port number
* @param configure Configuration block for TCP client options
* @returns Connected Socket instance
*/
suspend fun connect(
hostname: String,
port: Int,
configure: SocketOptions.TCPClientSocketOptions.() -> Unit = {}
): Socket
/**
* Connect to remote address
* @param remoteAddress Target socket address
* @param configure Configuration block for TCP client options
* @returns Connected Socket instance
*/
suspend fun connect(
remoteAddress: SocketAddress,
configure: SocketOptions.TCPClientSocketOptions.() -> Unit = {}
): Socket
/**
* Bind server socket at port to listen to hostname
* @param hostname Local hostname to bind to (default: "0.0.0.0")
* @param port Local port to bind to (default: 0 for auto-assignment)
* @param configure Configuration block for acceptor options
* @returns ServerSocket instance ready to accept connections
*/
suspend fun bind(
hostname: String = "0.0.0.0",
port: Int = 0,
configure: SocketOptions.AcceptorOptions.() -> Unit = {}
): ServerSocket
/**
* Bind server socket to listen to local address
* @param localAddress Local socket address to bind to (null for any address)
* @param configure Configuration block for acceptor options
* @returns ServerSocket instance ready to accept connections
*/
suspend fun bind(
localAddress: SocketAddress? = null,
configure: SocketOptions.AcceptorOptions.() -> Unit = {}
): ServerSocket
}Usage Examples:
import io.ktor.network.sockets.*
import io.ktor.network.selector.*
import kotlinx.coroutines.*
val selectorManager = SelectorManager()
// TCP Client - Connect to server
val clientSocket = aSocket(selectorManager).tcp().connect("localhost", 8080) {
noDelay = true
keepAlive = true
socketTimeout = 30000 // 30 seconds
}
// TCP Server - Bind and listen
val serverSocket = aSocket(selectorManager).tcp().bind("0.0.0.0", 8080) {
backlogSize = 50
reuseAddress = true
}
// Accept connections
while (true) {
val client = serverSocket.accept()
launch {
// Handle client connection
val connection = client.connection()
val request = connection.input.readUTF8Line()
connection.output.writeStringUtf8("Echo: $request")
connection.output.flush()
client.close()
}
}Interface representing a connected TCP socket with read/write capabilities.
/**
* Represents a connected socket
*/
interface Socket : ReadWriteSocket, ABoundSocket, AConnectedSocket, CoroutineScope
/**
* Represents both readable and writable socket
*/
interface ReadWriteSocket : ASocket, AReadable, AWritableInterface for TCP server sockets that can accept incoming connections.
/**
* Represents a server-bound socket ready for accepting connections
*/
interface ServerSocket : ASocket, ABoundSocket, Acceptable<Socket>
/**
* Represents a socket source, for example server socket
*/
interface Acceptable<out S : ASocket> : ASocket {
/**
* Suspends until a connection is available and returns it or throws if something goes wrong
* @returns accepted socket
* @throws IOException
*/
suspend fun accept(): S
}
/** The port number of the current server */
val ServerSocket.port: IntUsage Example:
import io.ktor.network.sockets.*
import io.ktor.network.selector.*
import kotlinx.coroutines.*
val selectorManager = SelectorManager()
// Create server socket
val serverSocket = aSocket(selectorManager).tcp().bind("localhost", 8080)
println("Server listening on port ${serverSocket.port}")
// Accept and handle connections
while (true) {
val clientSocket = serverSocket.accept()
println("Client connected from: ${clientSocket.remoteAddress}")
launch {
try {
val connection = clientSocket.connection()
// Read from client
val message = connection.input.readUTF8Line()
println("Received: $message")
// Write to client
connection.output.writeStringUtf8("Server received: $message")
connection.output.flush()
} catch (e: Exception) {
println("Error handling client: ${e.message}")
} finally {
clientSocket.close()
}
}
}Interfaces for reading and writing data to TCP sockets.
/**
* Represents a readable socket
*/
interface AReadable {
/**
* Attach channel for reading so incoming bytes appears in the attached channel
* Only one channel could be attached
* @param channel ByteChannel to attach for reading
* @returns a job that does supply data
*/
fun attachForReading(channel: ByteChannel): WriterJob
}
/**
* Represents a writable socket
*/
interface AWritable {
/**
* Attach channel for writing so bytes written to the attached channel will be transmitted
* Only one channel could be attached
* @param channel ByteChannel to attach for writing
* @returns a job that does transmit data from the channel
*/
fun attachForWriting(channel: ByteChannel): ReaderJob
}
/** Open a read channel, could be done only once */
fun AReadable.openReadChannel(): ByteReadChannel
/**
* Open a write channel, could be opened only once
* @param autoFlush whether returned channel do flush for every write operation
*/
fun AWritable.openWriteChannel(autoFlush: Boolean = false): ByteWriteChannelConvenience class that wraps a socket with its input and output channels.
/**
* Represents a connected socket with its input and output
*/
class Connection(
val socket: Socket,
val input: ByteReadChannel,
val output: ByteWriteChannel
)
/** Opens socket input and output channels and returns connection object */
fun Socket.connection(): ConnectionUsage Example:
import io.ktor.network.sockets.*
import io.ktor.network.selector.*
val selectorManager = SelectorManager()
// Connect to server
val socket = aSocket(selectorManager).tcp().connect("localhost", 8080)
// Get connection with I/O channels
val connection = socket.connection()
// Write data
connection.output.writeStringUtf8("Hello, Server!")
connection.output.flush()
// Read response
val response = connection.input.readUTF8Line()
println("Server response: $response")
// Alternative: Use raw socket I/O
val readChannel = socket.openReadChannel()
val writeChannel = socket.openWriteChannel(autoFlush = true)
writeChannel.writeStringUtf8("Another message")
val anotherResponse = readChannel.readUTF8Line()
// Clean up
socket.close()
selectorManager.close()Install with Tessl CLI
npx tessl i tessl/maven-io-ktor--ktor-network-tvosx64