Class: XRefreshServer::Server

Inherits:
GServer
  • Object
show all
Defined in:
lib/xrefresh-server/server.rb

Overview

server

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(port, host, max_connections, *args) ⇒ Server

Returns a new instance of Server.



10
11
12
13
14
15
# File 'lib/xrefresh-server/server.rb', line 10

def initialize(port, host, max_connections, *args)
    super
    @clients = Set.new
    @last_client_id = 0
    OUT.puts "#{green('Started server')} on #{blue("#{host}:#{port}")} (max #{max_connections} clients)"
end

Instance Attribute Details

#clientsObject

Returns the value of attribute clients.



8
9
10
# File 'lib/xrefresh-server/server.rb', line 8

def clients
  @clients
end

Instance Method Details

#process(client, msg) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/xrefresh-server/server.rb', line 36

def process(client, msg)
    # see windows implementation in http://github.com/darwin/xrefresh/tree/master/src/winmonitor/Server.cs#ProcessMessage
    case msg["command"]
        when "Hello"
            client.type = msg["type"] || '?'
            client.agent = msg["agent"] || '?'
            OUT.puts "Client #{client.name} [#{magenta(client.agent)}] has connected"
            client.send_about(VERSION, AGENT)
        when "Bye"
            @clients.delete(client)
            OUT.puts "Client #{client.name} has disconnected"
        when "SetPage"
            url = msg["url"] || '?'
            OUT.puts "Client #{client.name} changed page to #{blue(url)}"
    end
end

#serve(socket) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/xrefresh-server/server.rb', line 17

def serve(socket)
    socket.binmode
    @last_client_id += 1
    client = Client.new(@last_client_id, socket)
    @clients.add(client)
    loop do
        begin
            buffer = socket.gets(XREFRESH_MESSAGE_SEPARATOR)
        rescue
            # socket breaks on client disconnection
            break
        end
        break unless buffer
        message = buffer[0...-XREFRESH_MESSAGE_SEPARATOR.size]
        json = JSON.parse(message)
        process(client, json)
    end
end