Skip to content

cy6erGn0m/kotlinx-sockets

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

kotlinx sockets (🥚🥚🥚 incubating) status Download version

Kotlinx.sockets is a library to bring rich coroutines experience to NIO sockets, eliminate terrible callbacks and selector loops and related difficult code.

With the library and kotlin coroutines you can simply write async NIO code in usual synchronous style.

Consider example (full source)

fun main(args: Array<String>) {
    runBlocking { // start coroutines
        aSocket().tcp().connect(InetSocketAddress(InetAddress.getByName("google.com"), 80)).use { socket ->
            println("Connected") // now we are connected

            // chain of async write
            socket.send("GET / HTTP/1.1\r\n")
            socket.send("Host: google.com\r\n")
            socket.send("Accept: text/html\r\n")
            socket.send("Connection: close\r\n")
            socket.send("\r\n")

            // loop to read bytes and write to the console
            val bb = ByteBuffer.allocate(8192)
            while (true) {
                bb.clear()
                if (socket.read(bb) == -1) break // async read

                bb.flip()
                System.out.write(bb)
                System.out.flush()
            }

            println()
        }
    }
}

Getting started

Maven

<dependencies>
    <dependency>
        <groupId>org.jetbrains.kotlinx</groupId>
        <artifactId>kotlin-sockets</artifactId>
        <version>0.0.4</version>
    </dependency>
</dependencies>

<repositories>
    <repository>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
        <id>bintray-kotlin-kotlin-dev</id>
        <name>kotlin-dev</name>
        <url>http://dl.bintray.com/kotlin/kotlin-dev</url>
    </repository>
</repositories>

Gradle

repositories { 
    maven { url "http://dl.bintray.com/kotlin/kotlin-dev" } 
}

dependencies {
    compile 'org.jetbrains.kotlinx:kotlin-sockets:0.0.4'
}

Examples