Class: Pakyow::Realtime::WebSocket

Inherits:
Object
  • Object
show all
Includes:
Application::Helpers::Application, Application::Helpers::Connection
Defined in:
lib/pakyow/realtime/websocket.rb

Defined Under Namespace

Classes: Connection

Constant Summary collapse

Frame =
::Protocol::WebSocket::Frame

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, connection) ⇒ WebSocket

Returns a new instance of WebSocket.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/pakyow/realtime/websocket.rb', line 43

def initialize(id, connection)
  @id, @connection, @open = id, connection, false
  @logger = Logger.new(:sock, id: @id[0..7], output: Pakyow.global_logger, level: Pakyow.config.logger.level)
  @server = @connection.app.websocket_server

  response = Async::WebSocket::Adapters::Native.open(@connection.request, handler: Connection) do |socket|
    @socket = socket

    handle_open
    while message = socket.read
      handle_message(message)
    end
  rescue EOFError, Protocol::WebSocket::ClosedError
  ensure
    @socket&.close; shutdown
  end

  @connection.__getobj__.instance_variable_set(:@response, response)
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



41
42
43
# File 'lib/pakyow/realtime/websocket.rb', line 41

def id
  @id
end

Instance Method Details

#beatObject



79
80
81
# File 'lib/pakyow/realtime/websocket.rb', line 79

def beat
  transmit("beat")
end

#leaveObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



92
93
94
# File 'lib/pakyow/realtime/websocket.rb', line 92

def leave
  trigger_presence(:leave)
end

#open?Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/pakyow/realtime/websocket.rb', line 63

def open?
  @open == true
end

#shutdownObject



83
84
85
86
87
88
89
# File 'lib/pakyow/realtime/websocket.rb', line 83

def shutdown
  if open?
    @server.socket_disconnect(self)
    @open = false
    @logger.info "shutdown"
  end
end

#transmit(message, raw: false) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/pakyow/realtime/websocket.rb', line 67

def transmit(message, raw: false)
  if open?
    if raw
      @socket.write(message)
    else
      @socket.write(JSON.dump(payload: message))
    end

    @socket.flush
  end
end