Class: Whatup::Server::Server

Inherits:
Object
  • Object
show all
Includes:
DbInit, Redirection, WhatupLogger
Defined in:
lib/whatup/server/server.rb

Overview

rubocop:disable Metrics/ClassLength

Constant Summary collapse

Client =
Whatup::Server::Client

Instance Method Summary collapse

Methods included from WhatupLogger

#log

Methods included from Redirection

#redirect

Methods included from DbInit

setup_db!

Constructor Details

#initialize(ip: 'localhost', port:) ⇒ Whatup::Server::Server

Returns The created server.

Parameters:

  • ip (String) (defaults to: 'localhost')

    The ip address to run the server on

  • port (Integer)

    The port to run the server on



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/whatup/server/server.rb', line 34

def initialize ip: 'localhost', port:
  @ip = ip
  @port = port
  @address = "#{@ip}:#{@port}"

  @clients = []
  @rooms = []

  @pid = Process.pid
  @pid_file = "#{Dir.home}/.whatup.pid"

  DbInit.setup_db!
end

Instance Method Details

#clients_except(client) ⇒ Array<Whatup::Server::Client>

Returns All currently connected clients except for ‘client`.

Parameters:

Returns:



74
75
76
# File 'lib/whatup/server/server.rb', line 74

def clients_except client
  @clients.reject { |c| c == client }
end

#new_room!(clients: [], name:) ⇒ Whatup::Server::Room

Returns The created room.

Parameters:

  • clients (Array<Whatup::Server::Client>) (defaults to: [])

    Room’s inital clients

  • name (String)

    The room’s name

Returns:



82
83
84
85
86
# File 'lib/whatup/server/server.rb', line 82

def new_room! clients: [], name:
  Room.create!(name: name, clients: clients).tap do |room|
    @rooms << room
  end
end

#startObject

Starts the server.

The server continuously loops, and handle each new client in a separate thread.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/whatup/server/server.rb', line 52

def start
  log.info { "Starting a server with PID:#{@pid} @ #{@address} ... \n" }

  exit_if_pid_exists!
  connect_to_socket!
  write_pid!

  # Listen for connections, then accept each in a separate thread
  loop do
    Thread.new(@socket.accept) do |client|
      log.info { "Accepted new client: #{client.inspect}" }
      handle_client client
    end
  end
rescue SignalException # In case of ^c
  kill
end