-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket_connection.rb
66 lines (51 loc) · 1.36 KB
/
websocket_connection.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
60
61
62
63
64
65
66
require 'json'
class WebSocketConnection
OPCODE_TEXT = 0x01
def initialize(socket)
@socket = socket
end
def recv
fin_and_opcode = @socket.read(1).bytes[0].to_s(2)
fin = fin_and_opcode[0]
opcode = "0x%02x" % fin_and_opcode[4,4].to_i(2)
mask_and_length_indicator = @socket.read(1).bytes[0]
length_indicator = mask_and_length_indicator - 128
length = if length_indicator <= 125
length_indicator
elsif length_indicator == 126
@socket.read(2).unpack("n")[0]
else
@socket.read(8).unpack("Q>")[0]
end
mask = @socket.read(4).bytes
encoded = @socket.read(length).bytes
decoded = encoded.each_with_index.map do |byte, index|
byte ^ mask[index % 4]
end
if fin === '1'
case opcode
when "0x01"
return decoded.pack('c*')
when "0x08"
closeConnection
end
end
end
def send(message)
bytes = [0x80 | OPCODE_TEXT]
size = message.bytesize
bytes += if size <= 125
[size]
elsif size < 2**16
[126] + [size].pack("n").bytes
else
[127] + [size].pack("Q>").bytes
end
bytes += message.bytes
data = bytes.pack("C*")
@socket << data
end
def closeConnection
@socket.close
end
end