12

I have a TCP Server on Windows, and I want to send and receive text strings between the server and my Android device.

I spent alot of time searching for an example using Kotlin but I didn't find any useful code, so I'm now only able to create the socket and connect.

fun connect() {
    try{
        val soc = Socket("192.168.1.5", 1419)
        val dout = DataOutputStream(soc.getOutputStream())
        dout.writeUTF("1")

        dout.flush()
        dout.close()
        soc.close()
    }
    catch (e:Exception){
        e.printStackTrace()
    }
}
3
  • Welcome to SO! Could you please elaborate your question? You may also find this useful: how to ask Commented Jun 11, 2019 at 8:04
  • @user2340612 Thanks , i'm simply want to make a TCP Client using Kotlin, (connect to server , send and receive packets(in separated threads)) i can only connect and i didn't find a single post on SO showing how to do it in Kotlin all available codes are in Java
    – Tamer Ali
    Commented Jun 11, 2019 at 21:33
  • It works like java's java.net.socket for kotlin tcp. Or you can use ktor.
    – Sylhare
    Commented Nov 20, 2020 at 23:29

3 Answers 3

19

You can check this simple example. Hope it'll help you!

Server:

fun main() {
    val server = ServerSocket(9999)
    println("Server running on port ${server.localPort}")
    val client = server.accept()
    println("Client connected : ${client.inetAddress.hostAddress}")
    val scanner = Scanner(client.inputStream)
    while (scanner.hasNextLine()) {
        println(scanner.nextLine())
        break
    }
    server.close()
}

Client:

fun main() {
    val client = Socket("127.0.0.1", 9999)
    client.outputStream.write("Hello from the client!".toByteArray())
    client.close()
}
2
  • Thanks for your code , but this do the same as my code (connect and send packet)
    – Tamer Ali
    Commented Jun 11, 2019 at 18:58
  • 3
    Sorry, maybe I didn't get your question right. Your question is "How to send and receive strings through TCP connection using Kotlin" In the code snippet that I sent you the client is sending a string ("Hello from the client") the server which receives it and prints to the console. Could you elaborate a bit on your question, such as I can update my code snippet? Commented Jun 12, 2019 at 7:32
5

You can also do it with ktor, it's a kotlin based asynchronous framework. It uses coroutines natively which allow concurrency.

Use Kotlin 1.4 and ktor 1.6.0, add it to your build.gradle.kts:

plugins {
    kotlin("jvm") version "1.4.32"
}

dependencies {
    implementation("io.ktor:ktor-server-netty:1.6.0")
    implementation("io.ktor:ktor-network:1.6.0")
}

Then you can use the sockets, it's still a bit experimental but it's getting there, with newer version ktor-network is now necessary.

Here is the code:

Server:

suspend fun server() {
    val server = aSocket(ActorSelectorManager(Executors.newCachedThreadPool().asCoroutineDispatcher())).tcp()
        .bind(InetSocketAddress("127.0.0.1", 2323))
    println("Server running: ${server.localAddress}")
    val socket = server.accept()
    println("Socket accepted: ${socket.remoteAddress}")
    val input = socket.openReadChannel()
    val output = socket.openWriteChannel(autoFlush = true)
    val line = input.readUTF8Line()

    println("received '$line' from ${socket.remoteAddress}")
    output.writeFully("$line back\r\n".toByteArray())
}

Client:

suspend fun client() {
    val socket = aSocket(ActorSelectorManager(Dispatchers.IO)).tcp()
        .connect(InetSocketAddress("127.0.0.1", 2323))
    val input = socket.openReadChannel()
    val output = socket.openWriteChannel(autoFlush = true)

    output.writeFully("hello\r\n".toByteArray())
    println("Server said: '${input.readUTF8Line()}'")
}

Run them both:

fun main() {
    CoroutineScope(Dispatchers.Default).launch { server() }
    runBlocking { client() }
}

When you run them, the client will send a message, the server will respond and you should see something like this:

Server running: /127.0.0.1:2323
Socket accepted: /127.0.0.1:56215
received 'hello' from /127.0.0.1:56215
Server said: 'hello back'

Find more example on their documentation simple echo server

0

There are 2 important things based on my experiment:

  1. get permission in AndroidManifest.xml

    <uses-permission android:name="android.permission.INTERNET" />

  2. create the socket from a background thread, the following works for me:

    Executors.newSingleThreadExecutor().execute {
        val socket = Socket("192.168.0.15", 50000)
        val scanner = Scanner(socket.getInputStream())
        val printWriter = PrintWriter(socket.getOutputStream())
        while (scanner.hasNextLine()) {
            Log.d(TAG, "${ scanner.nextLine() }")
        }
    }

This is the source code in GitHub. There is a video of my experiment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.