diff --git a/src/WebSockets.jl b/src/WebSockets.jl index e9a2adc..f7ccc08 100644 --- a/src/WebSockets.jl +++ b/src/WebSockets.jl @@ -127,8 +127,8 @@ hasprotocol(s::String) = in(s,SUBProtocols) "Used to specify handshake response. See SUBProtocols" function addsubproto(name) - push!(SUBProtocols, string(name)) - return true + push!(SUBProtocols, string(name)) + return true end """ write_fragment(io, islast, data::Array{UInt8}, opcode) @@ -428,25 +428,25 @@ end """ Responds to a WebSocket handshake request. -Checks for required headers; sends Response(400) if they're missing or bad. -Otherwise, transforms client key into accept value, and sends Reponse(101). +Checks for required headers and subprotocols; sends Response(400) if they're missing or bad. Otherwise, transforms client key into accept value, and sends Reponse(101). +Function returns true for accepted handshakes. """ function websocket_handshake(request,client) if !haskey(request.headers, "Sec-WebSocket-Key") Base.write(client.sock, Response(400)) - return + return false end if get(request.headers, "Sec-WebSocket-Version", "13") != "13" response = Response(400) response.headers["Sec-WebSocket-Version"] = "13" Base.write(client.sock, response) - return + return false end key = request.headers["Sec-WebSocket-Key"] if length(decode(Base64,key)) != 16 # Key must be 16 bytes Base.write(client.sock, Response(400)) - return + return false end resp_key = generate_websocket_key(key) @@ -460,11 +460,12 @@ function websocket_handshake(request,client) response.headers["Sec-WebSocket-Protocol"] = request.headers["Sec-WebSocket-Protocol"] else Base.write(client.sock, Response(400)) - return + return false end end Base.write(client.sock, response) + return true end """ Implement the WebSocketInterface, for compatilibility with HttpServer.""" @@ -473,11 +474,19 @@ immutable WebSocketHandler <: HttpServer.WebSocketInterface end import HttpServer: handle, is_websocket_handshake +""" +Performs handshake. If successfull, establishes WebSocket type and calls +handler with the WebSocket and the original request. On exit from handler, closes websocket. No return value. +""" function handle(handler::WebSocketHandler, req::Request, client::HttpServer.Client) - websocket_handshake(req, client) + websocket_handshake(req, client) || return sock = WebSocket(client.id, client.sock) handler.handle(req, sock) - isopen(sock) && close(sock) + if isopen(sock) + try + close(sock) + end + end end function is_websocket_handshake(handler::WebSocketHandler, req::Request) is_get = req.method == "GET"