-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.rb
38 lines (33 loc) · 801 Bytes
/
server.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
require "socket"
require "set"
require "logger"
host, port = "0.0.0.0", ENV['PORT'] || 4466
server = TCPServer.open(host, port)
logger = Logger.new($stdout)
trap(:INT) do
logger.info "Shutting down"
exit
end
logger.info "Listening on #{host}:#{port}"
def broadcast(message, from_id, all_clients)
all_clients.each do |id, other|
other.puts message unless id == from_id
end
end
clients = {}
loop {
Thread.start(server.accept) do |client|
logger.info "Connecting to a client"
id = client.gets.chomp
logger.info "Connected to #{id}"
clients[id] = client
loop {
message = client.gets
break if message.nil?
broadcast(message, id, clients)
}
logger.info "Disconnected from #{id}"
clients.delete(id)
broadcast(id, nil, clients)
end
}