如何在 kotlin 中使用套接字 IO?

Sad*_*ife 5 socket.io kotlin

我想在我的 kotlin 应用程序中初始化套接字 IO。

我的问题在这里:

    private var mSocket: Socket? = null
{
    try {
        mSocket = IO.socket("http://chat.socket.io")
    } catch (URISyntaxException e) {
    }
}
Run Code Online (Sandbox Code Playgroud)

导入 com.github.nkzawa.socketio.client.IO

认不出来

Han*_*nny -1

在 Kotlin 中,您可以创建如下所示的Socket 客户端。所有异常也在这里处理。

fun pingYourTCPServerWith(message: String): String{
    try {
        val socket = Socket("<YOUR IP ADDRESS>", <YOUR PORT HERE>)
        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
    }
}
Run Code Online (Sandbox Code Playgroud)