Class: Rubame::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/rubame/rubame.rb

Instance Method Summary collapse

Constructor Details

#initialize(host, port) ⇒ Server

Returns a new instance of Server



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/rubame/rubame.rb', line 6

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

Instance Method Details

#acceptObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rubame/rubame.rb', line 20

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) ⇒ Object



65
66
67
68
69
70
71
72
73
# File 'lib/rubame/rubame.rb', line 65

def close(client)
  @reading.delete client.socket
  @clients.delete client.socket
  begin
    client.socket.close
  rescue
  end
  client.closed = true
end

#read(client) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/rubame/rubame.rb', line 41

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) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/rubame/rubame.rb', line 75

def run(&blk)
  readable, writable = IO.select(@reading, @writing, nil, 1)

  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

#stopObject



93
94
95
# File 'lib/rubame/rubame.rb', line 93

def stop
  @socket.close
end