-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket_server.rb
59 lines (48 loc) · 1.63 KB
/
websocket_server.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
require 'socket'
require 'digest/sha1'
require 'base64'
require_relative 'websocket_connection'
class WebSocketServer
WS_MAGIC_STRING = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
def initialize(options={path: '/', port: 4567, host: 'localhost'})
@path, port, host = options[:path], options[:port], options[:host]
@tcp_server = TCPServer.new(host, port)
end
def accept
socket = @tcp_server.accept
send_handshake(socket) && WebSocketConnection.new(socket)
end
private
def send_handshake(socket)
request_line = socket.gets
header = get_header(socket)
if (request_line =~ /GET #{@path} HTTP\/1.1/) && (header =~ /Sec-WebSocket-Key: (.*)\r\n/)
ws_accept = create_websocket_accept($1)
send_handshake_response(socket, ws_accept)
return true
end
send_400(socket)
false # reject the handshake
end
def get_header(socket, header = "")
(line = socket.gets) == "\r\n" ? header : get_header(socket, header + line)
end
def create_websocket_accept(key)
digest = Digest::SHA1.digest(key + WS_MAGIC_STRING)
Base64.encode64(digest)
end
def send_handshake_response(socket, ws_accept)
socket << "HTTP/1.1 101 Switching Protocols\r\n" +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
"Sec-WebSocket-Accept: #{ws_accept}\r\n"
end
def send_400(socket)
socket << "HTTP/1.1 400 Bad Request\r\n" +
"Content-Type: text/plain\r\n" +
"Connection: close\r\n" +
"\r\n" +
"Incorrect request"
socket.close
end
end