Skip to content

Unable to connect to server  #6

@xdindincx

Description

@xdindincx

Hi,

I have implemented this project in Kotlin:

`class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}

fun connectServer(v: View?) {
    val ipv4AddressView = findViewById<EditText>(R.id.IPAddress)
    val ipv4Address = ipv4AddressView.text.toString()
    val portNumberView = findViewById<EditText>(R.id.portNumber)
    val portNumber = portNumberView.text.toString()
    val postUrl = "http://$ipv4Address:$portNumber/"
    val postBodyText = "Hello"
    val mediaType: MediaType? = "text/plain; charset=utf-8".toMediaTypeOrNull()
    val postBody = RequestBody.create(mediaType, postBodyText)
    postRequest(postUrl, postBody)
}

fun postRequest(postUrl: String, postBody: RequestBody) {
    val client = OkHttpClient()
    val request: Request = Request.Builder()
        .url(postUrl)
        .post(postBody)
        .build()
    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            // Cancel the post on failure.
            call.cancel()

            // In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
            runOnUiThread {
                val responseText = findViewById<TextView>(R.id.responseText)
                responseText.text = "Failed to Connect to Server"
            }
        }

        @Throws(IOException::class)
        override fun onResponse(call: Call, response: Response) {
            // In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
            runOnUiThread {
                val responseText = findViewById<TextView>(R.id.responseText)
                try {
                    responseText.text = response.body!!.string()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    })
}

}`

The python server is up and running :

Can you help with this by any chance?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions