Reputation: 103
Due to an interest in the subject, I've decided to have a go at making a WebSocket client library for Kotlin using TCP.
So, I'm reading RFC6455 and it mentions that in the handshake, the server response should have a HTTP status line. Cool, I make my request:
GET / HTTP/1.1
Host: echo.websocket.org:80
Upgrade: websocket
Connection: Upgrade
Accept: */*
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: Dg8CY18ZTGbAkIzNhpO3mA==
and the server replies with
Connection: Upgrade
Sec-WebSocket-Accept: akyZ/0pr8WyuXVfejRWVAUGSW3k=
Upgrade: websocket
As you can see, no HTTP status line. Did I miss something in RFC6455, is my code dumb?
code (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
}
code (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)
}
}
}
}
to run:
WebSocket("ws", "echo.websocket.org", 80)
Upvotes: -1
Views: 276
Reputation: 103
SOLVED
I was not storing the result of readLine() in a variable, causing me to essentially discard every odd line in the response. Thanks to user207421 for pointing it out!
Upvotes: 0