使用kotlin和okhttp写一个websocket示例代码
时间: 2023-03-11 12:44:39 浏览: 226
您可以使用以下示例代码编写websocket程序:import okhttp3.*class WebSocketExample {
private val client = OkHttpClient() fun run(){
val request = Request.Builder().url("wss://echo.websocket.org").build()
val listener = EchoWebSocketListener()
val ws = client.newWebSocket(request, listener) // Send text message to server
ws.send("Hello, Server!") // Send binary message to server
val bytes = ByteString.decodeHex("deadbeef")
ws.send(bytes) // Schedule ping
val ping = "Ping"
val pong = "Pong"
val pingInterval = 10L
val scheduler = Executors.newSingleThreadScheduledExecutor()
scheduler.scheduleAtFixedRate({
ws.send(ping)
}, 0, pingInterval, TimeUnit.SECONDS)
}
}class EchoWebSocketListener : WebSocketListener() { override fun onMessage(webSocket: WebSocket, text: String) {
if(text == "Pong"){
println("Received pong")
}else{
println("Received: ${text}")
}
} override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
webSocket.close(NORMAL_CLOSURE_STATUS, null)
println("Closing: ${code} ${reason}")
}
}fun main(args: Array<String>) {
val example = WebSocketExample()
example.run()
}
阅读全文