lib/em-midori/server.rb in em-midori-0.0.9.2 vs lib/em-midori/server.rb in em-midori-0.0.9.3
- old
+ new
@@ -1,16 +1,26 @@
+##
+# Logics to EventMachine TCP Server, running inside +EM::Connection+
+# @attr [Midori::Request] request
+# @attr [Class] api inherited from Midori::API
+# @attr [Midori::WebSocket] websocket websocket instance
+# @attr [Midori::EventSource] eventsource eventsource instance
module Midori::Server
attr_accessor :request, :api, :websocket, :eventsource
+ # @param [Class] api inherited from Midori::API
+ # @param [Logger] logger global logger
def initialize(api, logger)
@api = api
@logger = logger
@request = Midori::Request.new
@websocket = Midori::WebSocket.new(self)
@eventsource = Midori::EventSource.new(self)
end
+ # Logics of receiving data
+ # @param [String] data raw data
def receive_data(data)
->() { async_internal(Fiber.new do
start_time = Time.now
data = StringIO.new(data)
port, ip = Socket.unpack_sockaddr_in(get_peername)
@@ -24,10 +34,12 @@
now_time = Time.now
@logger.info "#{@request.ip} - - \"#{@request.method} #{@request.path} #{@request.protocol}\" #{@response.status} #{(now_time.to_f - start_time.to_f).round(5)}".green
end) }.call
end
+ # Logics of receiving new request
+ # @param [String] data raw data
def receive_new_request(data)
begin
@request.parse(data)
@response = @api.receive(request, self)
call_event(:open) if @request.websocket?
@@ -42,10 +54,12 @@
send_data @response
close_connection_after_writing
end
end
+ # Logics of receiving WebSocket request
+ # @param [String] data raw data
def websocket_request(data)
@websocket.decode(data)
case @websocket.opcode
when 0x1, 0x2
call_event(:message, [@websocket.msg])
@@ -67,9 +81,12 @@
@logger.error e.inspect.red
@logger.warn e.backtrace.join("\n").yellow
close_connection_after_writing
end
+ # To call a websocket event if it exist
+ # @param [Symbol] event event name
+ # @param [Array] args arg list
def call_event(event, args = [])
(-> { @websocket.instance_exec(*args, &@websocket.events[event]) }.call) unless @websocket.events[event].nil?
end
end