WebSocket握手响应缺少HTTP状态行

时间:2020-03-17 09:04:17

标签: kotlin websocket tcp rfc6455

由于对该主题感兴趣,我决定尝试使用TCP为Kotlin创建WebSocket客户端库。

因此,我正在阅读RFC6455,它提到在握手中,服务器响应应具有HTTP状态行。酷,我提出要求:

GET / HTTP/1.1
Host: echo.websocket.org:80
Upgrade: websocket
Connection: Upgrade
Accept: */*
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: Dg8CY18ZTGbAkIzNhpO3mA==

,服务器回复

Connection: Upgrade
Sec-WebSocket-Accept: akyZ/0pr8WyuXVfejRWVAUGSW3k=
Upgrade: websocket

如您所见,没有HTTP状态行。我是否错过了RFC6455中的内容,我的代码很笨吗?

代码(PayloadFactory.kt):

fun createSecWebSocketKey(): String? {
    val bytes = ByteArray(16)
    SecureRandom.getInstanceStrong().nextBytes(bytes)
    return String(Base64.getEncoder().encode(bytes)!!)
}

fun createOpeningHandshake(host: String, path: String = "/", port: Int = 80, protocolVersion: Int = 13): String
{
    // I'm aware path isn't used yet, that's something I plan to implement but haven't yet.
    var handshake = ""
    handshake += "GET / HTTP/1.1\r\n"
    handshake += "Host: $host:$port\r\n"
    handshake += "Upgrade: websocket\r\n"
    handshake += "Connection: Upgrade\r\n"
    handshake += "Accept: */*\r\n"
    handshake += "Sec-WebSocket-Version: $protocolVersion\r\n"
    handshake += "Sec-WebSocket-Key: ${createSecWebSocketKey()}\r\n\r\n"
    return handshake
}

代码(WebSocket.kt):

class WebSocket(protocol: String, host: String, port: Int = 80, protocolVersion: Int = 13) {
    private val client: Socket = Socket(host, port)
    private val globallyUniqueIdentifier = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

    init {
        val handshake = createOpeningHandshake(host, protocolVersion = protocolVersion)
        println("============CLIENT HANDSHAKE============")
        println(handshake)
        client.getOutputStream().write(handshake.toByteArray())
        println("============SERVER RESPONSE=============")
        val input = BufferedReader(InputStreamReader(client.getInputStream()))
        while (true)
        {
            if (input.readLine() != null) {
                val line = input.readLine()
                println(line)
            }
        }
    }
}

运行: WebSocket("ws", "echo.websocket.org", 80)

1 个答案:

答案 0 :(得分:0)

已解决

我没有将readLine()的结果存储在变量中,这导致我实际上丢弃了响应中的每条奇数行。感谢user207421指出来!

相关问题