Class: Midori::Connection

Inherits:
Object
  • Object
show all
Includes:
Server
Defined in:
lib/midori/connection.rb

Overview

States of a connection

Instance Attribute Summary collapse

Attributes included from Server

#api, #eventsource, #request, #websocket

Instance Method Summary collapse

Methods included from Server

#call_event, #receive_data, #receive_new_request, #server_initialize, #websocket_request

Constructor Details

#initialize(socket) ⇒ Connection

Init Connection with socket

Parameters:

  • socket (IO)

    raw socket



12
13
14
15
16
17
18
19
# File 'lib/midori/connection.rb', line 12

def initialize(socket)
  @registered = false
  @socket = socket
  @monitor = nil
  @close_flag = false
  @data = ''
  listen(socket)
end

Instance Attribute Details

#dataString

Returns string buffer of data to send.

Returns:

  • (String)

    string buffer of data to send



8
9
10
# File 'lib/midori/connection.rb', line 8

def data
  @data
end

Instance Method Details

#close_connectionObject

Close the connection



50
51
52
53
# File 'lib/midori/connection.rb', line 50

def close_connection
  EventLoop.deregister @socket
  @socket.close
end

#close_connection_after_writingObject

Close the connection after writing



56
57
58
# File 'lib/midori/connection.rb', line 56

def close_connection_after_writing
  @close_flag = true
end

#listen(socket) ⇒ Object

Register events of connection

Parameters:

  • socket (IO)

    raw socket



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/midori/connection.rb', line 23

def listen(socket)
  EventLoop.register(socket, :rw) do |monitor|
    @monitor = monitor
    if monitor.readable?
      receive_data(monitor)
    end
    if monitor.writable?
      if !@data == ''
        # :nocov:
        # Leave for corner cases
        monitor.io.write_nonblock(@data)
        @data = ''
        # :nocov:
      elsif @close_flag
        close_connection
      end
    end
  end
end

#send_data(data) ⇒ Object

Send message to client

Parameters:

  • data (String)

    data to send



45
46
47
# File 'lib/midori/connection.rb', line 45

def send_data(data)
  @monitor.writable? ? @socket.write_nonblock(data) : @data << data
end