2
votes

I wait for clients with ServerSocket.accept() and then process like this:

val in = new BufferedReader(new InputStreamReader(socket.getInputStream()))
var line = in.readLine()
while (line != null) {
//...
line = in.readLine()
}

How do I know that the client finished sending the headers, in order to send a response?

Specifically I mean these headers:

GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com

Like described: http://en.wikipedia.org/wiki/WebSocket

I tried:

if (line.contains("\r\n")) {
    println("1")
}
if (line.contains("\r")) {
    println("2")
}
if (line.contains("\n")) {
    println("3")
}

But it doesn't work...

Something which worked, was line.isEmpty(). But it's strange, since the stream should contain something and all the contains return false...

2

2 Answers

2
votes

readLine removes the \r\n from the end of each line it reads, thus an empty line is just "" without any \r or \n characters.

0
votes

A websocket handshake is just a http request. Thus you should be able to tell when the headers end by the carriage return/line feed characters (\r\n).

What client are you using? Perhaps the client has a problem?

You know that you don't need to build a websockets library yourself. There are many open source alternatives out there like the one as part of netty.