Client TCP Kotlin

I’m create a socket in my App Kotlin

        val client = Socket("192.168.137.235", 9100)
        client.outputStream.write("Hello from the client!".toByteArray())
        client.close()

But when you start the application and executed that code shows the following error

2019-10-17 11:50:47.444 1924-1924/com.prueba.print E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.prueba.print, PID: 1924
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
at java.net.Socket.connect(Socket.java:570)
at java.net.Socket.(Socket.java:450)
at java.net.Socket.(Socket.java:218)
at com.prueba.print.MainActivity.printTCPIP(MainActivity.kt:114)
at com.prueba.print.MainActivity.access$printTCPIP(MainActivity.kt:42)
at com.prueba.print.MainActivity$onCreate$2.onClick(MainActivity.kt:106)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:782)
at android.view.View$PerformClick.run(View.java:25945)
at android.os.Handler.handleCallback(Handler.java:874)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Thanks…!!

It may look like there’s no error message there, but the exception itself has the message: you can’t perform networking on the main thread, on Android. So this code that’ll just work just fine at the CLI, it won’t work on Android unless you get some other thread to handle it.

c.f. https://stackoverflow.com/questions/55455957/networkonmainthreadexception-with-url-readtext-in-kotlin-coroutines