how to use socket IO in kotlin?

前端 未结 4 1457
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 00:07

I want to initialize socket IO in my kotlin app.

my problem is here :

    private var mSocket: Socket? = null
{
    try {
        mSocket = IO.socket         


        
4条回答
  •  有刺的猬
    2020-12-21 01:07

    In Kotlin you can make a Socket Client like the following. All the Exceptions are handled here too.

    fun pingYourTCPServerWith(message: String): String{
        try {
            val socket = Socket("", )
            socket.use {
    
                var responseString : String? = null
    
                it.getOutputStream().write(message.toByteArray())
                val bufferReader = BufferedReader(InputStreamReader(it.inputStream))
                while (true) {
                    val line = bufferReader.readLine() ?: break
                    responseString += line
                    if (line == "exit") break
                }
                println("Received: $responseString")
                bufferReader.close()
                it.close()
                return responseString!!
            }
        }catch (he: UnknownHostException){
            val exceptionString = "An exception occurred:\n ${he.printStackTrace()}"
            return   exceptionString
        }catch (ioe: IOException){
            val exceptionString = "An exception occurred:\n ${ioe.printStackTrace()}"
            return   exceptionString
        } catch (ce: ConnectException){
            val exceptionString = "An exception occurred:\n ${ce.printStackTrace()}"
            return   exceptionString
        }catch (se: SocketException){
            val exceptionString = "An exception occurred:\n ${se.printStackTrace()}"
            return   exceptionString
        }
    }
    

提交回复
热议问题