class Rubame::Server

Public Class Methods

new(host, port) click to toggle source
# File lib/rubame/server.rb, line 3
def initialize(host, port)
  Socket.do_not_reverse_lookup
  @hostname = host
  @port = port

  @reading = []
  @writing = []

  @clients = {} # Socket as key, and Client as value

  @socket = TCPServer.new(@hostname, @port)
  @reading.push @socket
end

Public Instance Methods

accept() click to toggle source
# File lib/rubame/server.rb, line 17
def accept
  socket = @socket.accept_nonblock
  @reading.push socket
  handshake = WebSocket::Handshake::Server.new
  client = Rubame::Client.new(socket, handshake, self)
  
  while (line = socket.gets)
    client.handshake << line
    break if client.handshake.finished?
  end

  if client.handshake.valid?
    @clients[socket] = client
    client.write handshake.to_s
    client.opened = true
    return client
  else
    close(client)
  end

  nil
end
close(client) click to toggle source
# File lib/rubame/server.rb, line 62
def close(client)
  @reading.delete client.socket
  @clients.delete client.socket
  client.socket.close
rescue
  # do nothing
ensure
  client.closed = true
end
read(client) click to toggle source
# File lib/rubame/server.rb, line 40
def read(client)
  pairs = client.socket.recvfrom(2000)
  messages = []

  if pairs[0].length == 0
    close(client)
  else
    client.frame << pairs[0]

    while (f = client.frame.next)
      if f.type == :close
        close(client)
        return messages
      else
        messages.push f
      end
    end
  end

  messages
end
run(&blk) click to toggle source
# File lib/rubame/server.rb, line 72
def run(&blk)
  readable, _writable = IO.select(@reading, @writing)

  if readable
    readable.each do |socket|
      client = @clients[socket]
      if socket == @socket
        client = accept
      else
        msg = read(client)
        client.messaged = msg
      end

      blk.call(client) if client && blk
    end
  end
end
stop() click to toggle source
# File lib/rubame/server.rb, line 90
def stop
  @socket.close
end