【问题标题】:WebSocket Implementation in Android using Kotlin使用 Kotlin 在 Android 中实现 WebSocket
【发布时间】:2019-11-30 14:47:01
【问题描述】:

我正在尝试使用 Kotlin 在 android 中使用 Web 套接字实现简单的消息传输。 我是 kotlin 的新手,我从工作的 java 代码中手动迁移了我的代码。 但是我的代码不起作用,没有任何显示 - 即使使用 network_security_config 作为

<network-security-config>
<base-config cleartextTrafficPermitted="true" >
</base-config>

而我的 websocket 实现代码是 ->

class MainActivity : AppCompatActivity() {
    private lateinit var client: OkHttpClient
    private var startButton: Button? = null
    private var outputText: TextView? = null


    private inner class EchoWebSocketListener : WebSocketListener() {
        private var NORMAL_CLOSURE_STATUS: Int = 1000

        override fun onOpen(webSocket: WebSocket, response: Response) {
            webSocket.send("Hola there!")
            webSocket.send("cool")
            webSocket.close(NORMAL_CLOSURE_STATUS,"GoodBye!!")
        }

        override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
            output("Receiving "+ bytes.toString())
        }

        override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
            webSocket.close(NORMAL_CLOSURE_STATUS, null)
            output("Closing : "+ code + "/" + reason)
        }

        override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
            output("Error : " + t.message)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        startButton = findViewById<Button>(R.id.start)
        outputText = findViewById<TextView>(R.id.output)
        client = OkHttpClient()
        startButton!!.setOnClickListener{
            start()
        }
    }

    private fun start() {
        val request: Request = Request.Builder().url("ws://echo.websocket.org").build()
        val listener: EchoWebSocketListener = EchoWebSocketListener()
        val ws: WebSocket = client.newWebSocket(request, listener)
        client.dispatcher().executorService().shutdown()
    }

    private fun output(s: String) {
        runOnUiThread({
            object : Runnable {
                override fun run() {
                    outputText!!.setText(outputText!!.text.toString() + "\n\n" + s)
                }
            }
        })
    }
}

非常感谢任何帮助

【问题讨论】:

    标签: android kotlin websocket


    【解决方案1】:

    我并没有过多地研究您的代码,但乍一看,您似乎在收到 onOpen 事件后就立即关闭了连接。我想这可能是你的问题。

    【讨论】:

      猜你喜欢
      • 2014-08-17
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 2020-08-23
      • 2013-11-28
      相关资源
      最近更新 更多