Class: Rakie::TCPServerChannel

Inherits:
TCPChannel show all
Defined in:
lib/rakie/tcp_server_channel.rb

Constant Summary

Constants inherited from TCPChannel

Rakie::TCPChannel::LOCAL_HOST

Constants inherited from Channel

Channel::DEFAULT_BUFFER_SIZE

Instance Attribute Summary

Attributes inherited from Channel

#delegate

Instance Method Summary collapse

Methods inherited from Channel

#close, #closed?, #eof?, #handle_write, #on_detach, #on_write, #read, #write

Constructor Details

#initialize(host, port, delegate) ⇒ TCPServerChannel #initialize(host, port) ⇒ TCPServerChannel #initialize(port) ⇒ TCPServerChannel

Returns a new instance of TCPServerChannel.

Parameters:

  • host (String) (defaults to: LOCAL_HOST)
  • port (Integer) (defaults to: 3001)
  • delegate (Object) (defaults to: nil)


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rakie/tcp_server_channel.rb', line 9

def initialize(host=LOCAL_HOST, port=3001, delegate=nil)
  socket = nil
  
  if port == nil
    port = host
    host = LOCAL_HOST
  end
  
  socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM)
  socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1)
  socket.bind(Socket.pack_sockaddr_in(port, host))
  socket.listen(255)

  @clients = []

  super(host, port, delegate, socket)
end

Instance Method Details

#acceptObject



62
63
64
# File 'lib/rakie/tcp_server_channel.rb', line 62

def accept
  @clients.shift
end

#on_read(io) ⇒ Object

Parameters:

  • io (Socket)


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
# File 'lib/rakie/tcp_server_channel.rb', line 28

def on_read(io)
  begin
    ret = io.accept_nonblock
    # @type client_io [Socket]
    client_io = ret[0]
    # @type client_info [Addrinfo]
    client_info = ret[1]
    client_name_info = client_info.getnameinfo
    client_host = client_name_info[0]
    client_port = client_name_info[1]
    channel = TCPChannel.new(client_host, client_port, nil, client_io)

    if @delegate != nil
      Log.debug("TCPServerChannel has delegate")
      @delegate.on_accept(channel)

    else
      Log.debug("TCPServerChannel no delegate")
      @clients << channel
    end

    Log.debug("TCPServerChannel accept #{channel}")

  rescue IO::EAGAINWaitReadable
    Log.debug("TCPServerChannel accept wait")

  rescue
    Log.debug("TCPServerChannel Accept failed #{io}")
    return Event::HANDLE_FAILED
  end

  return Event::HANDLE_CONTINUED
end