title: How to use socket in Android with Kotlin
body: <p>I want to achieve something in Android using Kotlin to do:</p>
  <p>If I click a button on the app, the app sends a word to a TCP server (which I wrote with python). The server will send back another word, and the app will show a toast message.</p>
  <p>Here is what I have done so far, I can figure out the sending part but I can't manage to make it keep listening to the socket to hear from the server.</p>
  <p>I am trying to use coroutine but after finding all the resources online, this is as best as I can get.</p>
  <p>Also, I am not sure if I am setting the IP address in the correct manner.</p>
  <p>Thank you in advance for your help!</p>
  <p>'''</p>
  <pre><code>class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
  
      val sendBtn = findViewById&lt;Button&gt;(R.id.sendBtn )
      val ipBtn = findViewById&lt;Button&gt;(R.id.ipBtn)
      val ipInput = findViewById&lt;TextView&gt;(R.id.ipInput)
  
      var ipAddress: String = &quot;192.168.0.101&quot;
  
      // Below is my attempt to keep listening to the socket, if commented, the sending would work. 
      // My guess is the IO thread is caught in the while loop so the other coroutines cannot use 
      // IO thread to send to the server.
      CoroutineScope(IO).launch{
          val socket = Socket(ipAddress, 9999)
          var text = &quot;&quot;
          while (true) {
              text = BufferedReader(InputStreamReader(socket.inputStream)).readLine()
              // if text is not null
              // Toast.makeText(this@MainActivity, &quot;Set IP&quot;, Toast.LENGTH_SHORT).show()
          }
      }
  
      suspend fun sendMessage(message:String){
          val socket = Socket(ipAddress, 9999)
          socket.outputStream.write(message.toByteArray())
          socket.close()
      }
  
      ipBtn.setOnClickListener {
          Toast.makeText(this@MainActivity, &quot;Set IP&quot;, Toast.LENGTH_SHORT).show()
          ipAddress = ipInput.text.toString()
      }
  
      sendBtn .setOnClickListener {
          CoroutineScope(IO).launch {
              Log.d(&quot;TAG&quot;, &quot;message&quot;)
              sendMessage(&quot;record&quot;)
          }
      }
  </code></pre>
  <p>'''</p>