Class: Hole::Server

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

Instance Method Summary collapse

Constructor Details

#initialize(ip, port) ⇒ Server



3
4
5
6
7
8
9
10
# File 'lib/system/server/server.rb', line 3

def initialize(ip, port)
  @server = TCPServer.open(ip, port)
  @connections = {}
  @rooms = {}
  @clients = {}
  initialize_connections
  run
end

Instance Method Details

#initialize_connectionsObject



12
13
14
15
16
# File 'lib/system/server/server.rb', line 12

def initialize_connections
  @connections[:server] = @server
  @connections[:rooms] = @rooms
  @connections[:clients] = @clients
end

#listen_user_messages(username, client) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/system/server/server.rb', line 37

def listen_user_messages(username, client)
  loop do
    msg = client.gets.chomp
    @connections[:clients].each do |other_name, other_client|
      other_client.puts "#{username.to_s}: #{msg}".green.on_black unless other_name == username
    end
  end
end

#runObject



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

def run
  loop do
    Thread.start(@server.accept) do |client|
      username = client.gets.chomp.to_sym

      @connections[:clients].each do |other_name, other_client|
        if username == other_name || client == other_client
          client.puts 'Sorry, but this name already exist'.red
          Thread.kill self
        end
      end
      puts "#{username} #{client}"
      @connections[:clients][username] = client
      client.puts 'Connection established. Thank you for joining! Happy chatting.'.light_blue
      listen_user_messages(username, client)
    end
  end
end