Class: EventMachine::WebSocketCodec::Encoder

Inherits:
Object
  • Object
show all
Includes:
Protocol
Defined in:
lib/em-ws-client/encoder.rb

Overview

Internal: Encodes messages into WebSocket frames based on RFC 6455

Constant Summary

Constants included from Protocol

Protocol::BINARY_FRAME, Protocol::CLOSE, Protocol::CONTINUATION, Protocol::PING, Protocol::PONG, Protocol::TEXT_FRAME

Instance Method Summary collapse

Instance Method Details

#close(code, message) ⇒ Object

create a close payload with code



58
59
60
# File 'lib/em-ws-client/encoder.rb', line 58

def close code, message
  encode [code ? code : 1000, message].pack("nA*"), CLOSE
end

#encode(data, opcode = TEXT_FRAME) ⇒ Object

Encode a standard payload to a hybi10 WebSocket frame



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
# File 'lib/em-ws-client/encoder.rb', line 13

def encode data, opcode=TEXT_FRAME
  frame = []
  frame << (opcode | 0x80)

  packr = "CC"

  if opcode == TEXT_FRAME
    data.force_encoding("UTF-8")

    if !data.valid_encoding?
      raise "Invalid UTF!"
    end
  end

  # append frame length and mask bit 0x80
  len = data ? data.bytesize : 0
  if len <= 125
    frame << (len | 0x80)
  elsif len < 65536
    frame << (126 | 0x80)
    frame << len
    packr << "n"
  else
    frame << (127 | 0x80)
    frame << len
    packr << "L!>"
  end

  # generate a masking key
  key = rand(2 ** 31)

  # mask each byte with the key
  frame << key
  packr << "N"

  #puts "op #{opcode} len #{len} bytes #{data}"
  # Apply the masking key to every byte
  len.times do |i|
    frame << ((data.getbyte(i) ^ (key >> ((3 - (i % 4)) * 8))) & 0xFF)
  end

  frame.pack("#{packr}C*")
end

#ping(data = nil) ⇒ Object

create a ping payload



63
64
65
# File 'lib/em-ws-client/encoder.rb', line 63

def ping data=nil
  encode data, PING
end

#pong(data = nil) ⇒ Object

create a pong payload



68
69
70
# File 'lib/em-ws-client/encoder.rb', line 68

def pong data=nil
  encode data, PONG
end