1

I have simple client and server socket application connecting each other based on this code. The problem is i can send and get values but when client getting answer from server continue to send message.

Where is my problem?

here is server : My server socket is in Service.I execute it when service starts

class SocketService: Service() {

override fun onBind(intent: Intent?): IBinder? {
    return null
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    thread { ClientHandler().run() }
    return START_STICKY
}

internal inner class ClientHandler() : Runnable{
    override fun run() {
        val server = ServerSocket(5000)
        val client = server.accept()
        var reader = BufferedReader(InputStreamReader(client.getInputStream()))
        var writer = PrintWriter(client.getOutputStream())
        try {
            receiveString = reader.readLine()
            while(receiveString != "")
            {
                println(receiveString)
                writer.write("hello from server" + "\n")
                writer.flush()
            }

            writer.close();
            reader.close();
            server.close();
            client.close();

        } catch (ex: Exception) {
            Timber.e("$TAG $formatted $ex")
        }
    }

}

Here my client :

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    connectToPaymentService()
}

fun connectToPaymentService(){
    thread { ThreadopenPort().run() }
}


internal inner class ThreadopenPort : Runnable {
    override fun run() {
        val socket: Socket
        try {
            socket = Socket(SERVER_IP, SERVER_PORT)
            output = PrintWriter(socket.getOutputStream())
            input = BufferedReader(InputStreamReader(socket.getInputStream()))

            rMessage = input!!.readLine()
            println(rMessage)
            while(rMessage != ""){
                output!!.write("hello from client" + "\n")
                output!!.flush()
                rMessage = input!!.readLine()
            }

            output!!.close();
            input!!.close();
            socket.close();


        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}
paulsm4
  • 114,292
  • 17
  • 138
  • 190
saulyasar
  • 797
  • 1
  • 17
  • 45
  • SUGGESTION: try "use" blocks: https://kotlinlang.org/docs/tutorials/kotlin-for-py/scoped-resource-usage.html – paulsm4 Nov 13 '20 at 06:47
  • @paulsm4 i checked but looks like not useful can you give example? – saulyasar Nov 13 '20 at 08:03
  • Your server is only reading lines. It never sends a line. But your client is trying to read lines. Your client will hang in .readLine() as nothing comes in. – blackapps Nov 13 '20 at 09:07
  • @blackapps The logic is first client send 'hello from client' then server ill send 'hello from server' and then i understand they are connected each other but problem is after get this message i'm continue to getting message 'hello from client' – saulyasar Nov 13 '20 at 13:06
  • No your logic is different. The client does not first send a line to the server. The client first tries to read a line. But the server never sends a line. So the client 'hangs' in .readLine(). You dont know your logic/protocol. – blackapps Nov 13 '20 at 20:43
  • @blackapps i solved problem with edited my code but now i have another problem can you check? https://stackoverflow.com/questions/64822819/connect-failed-econnrefused-connection-refused – saulyasar Nov 14 '20 at 05:22

1 Answers1

1

@saulyasar -

  1. If I gave you an example, it would be in Java, not Kotlin ;)
  2. Stylistically, you should prefer "use()" to explicit "close()". It won't help your immediate problem - but it's a good habit :)
  3. Your problem is: while(receiveString != ""). You loop ... but "receiveString" is never modified. So the loop never terminates. Whoops!

SUGGESTED ALTERNATIVE:

Assignment not allowed in while expression?

BufferedReader(reader).use { r ->
    r.lineSequence().forEach {
        println(it)
    }
}

I believe this idiom can be successfully applied to your socket "read" loop.

Please post back what you find :)

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • Thanks for help i found solution another way but now i have another problem can you check? https://stackoverflow.com/questions/64822819/connect-failed-econnrefused-connection-refused – saulyasar Nov 14 '20 at 05:23