我正在尝试连接 SocketIO,但我从 Android 端收到此错误(iOS 有效):
这是我在 Android 中所做的事情:
override fun init() = callbackFlow {
val accessToken = tokenStorage.accessToken ?: return@callbackFlow
val option = IO.Options.builder()
.setUpgrade(false)
.setTransports(arrayOf(WebSocket.NAME))
.setExtraHeaders(mapOf("Authorization" to listOf("Bearer ".plus(accessToken)))) // Without this I'll the the Unauthorized 401
.build()
socket = IO.socket(BuildConfig.WS_URL, option)
socket.on(Socket.EVENT_CONNECT) {
trySend(true)
}
socket.on(Socket.EVENT_CONNECT_ERROR) {
Log.d("xxxx", "asSocketPayload error: ${it[0]}")
}
socket.on(DEFAULT_EVENT) {
it[0].asSocketPayload()
}
socket.connect()
awaitClose {
socket.disconnect()
}
}
我使用的是套接字IO客户端2.0.0
谢谢
客户端好像不支持添加header。所以我尝试使用 OkHttpClient 代替。它就像一个魅力。 这是它的简短版本:
override fun init() = callbackFlow {
val accessToken = tokenStorage.accessToken ?: return@callbackFlow
val client = OkHttpClient()
val request = Request.Builder()
.url(BuildConfig.WS_URL)
.addHeader("Authorization", "Bearer $accessToken")
.build()
val webSocketListener = object : WebSocketListener() {
override fun onOpen(webSocket: okhttp3.WebSocket, response: Response) {
trySend(true)
}
override fun onMessage(webSocket: okhttp3.WebSocket, text: String) {
// Handle incoming message
Log.d("xxxx", "asSocketPayload: $text")
}
override fun onClosing(webSocket: okhttp3.WebSocket, code: Int, reason: String) {
// Handle closing connection
Log.d("xxxx", "asSocketPayload: $reason")
}
override fun onFailure(webSocket: okhttp3.WebSocket, t: Throwable, response: Response?) {
// Handle failure
Log.d("xxxx", "asSocketPayload: $t -- $response")
}
}
client.newWebSocket(request, webSocketListener)
awaitClose {
client.dispatcher.executorService.shutdown()
}
}
请注意: 在这种情况下,套接字 enpoint 应使用
wss://
而不是 https://
。
我会将其标记为该问题的答案。因此,如果您有使用 SocketIO 客户端的解决方案,请在下面告诉我们。谢谢!