【发布时间】: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)
}
}
})
}
}
非常感谢任何帮助
【问题讨论】: