class Rubame::Server

Public Class Methods

new(host, port) click to toggle source
# File lib/vendor/rubame.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/vendor/rubame.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
  return nil
end
close(client) click to toggle source
# File lib/vendor/rubame.rb, line 63
def close(client)
  @reading.delete client.socket
  @clients.delete client.socket
  begin
    client.socket.close
  ensure
    client.closed = true
  end
end
read(client) click to toggle source
# File lib/vendor/rubame.rb, line 38
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

  return messages

end
run(&blk) click to toggle source
# File lib/vendor/rubame.rb, line 73
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 and blk
    end
  end
end
stop() click to toggle source
# File lib/vendor/rubame.rb, line 91
def stop
  @socket.close
end