snipplets.dev/code/Crystal/UNIXSockets/by_faustinoaq/server.cr
2023-09-26 22:05:13 +03:00

39 lines
643 B
Crystal

require "socket"
server = UNIXServer.new("/tmp/myapp.sock")
CLIENTS = [] of UNIXSocket
Signal::INT.trap {
puts "closing server..."
server.close
exit
}
def on_message(client)
loop {
msg = client.gets
if msg == "quit"
puts "deleting client..."
CLIENTS.delete client
pp CLIENTS.size
break
else
yield msg
end
}
end
loop {
puts "waiting for client on /tmp/myapp.sock"
new_client = server.accept
spawn {
on_message(new_client) { |msg|
CLIENTS.each { |client|
client.puts msg unless client == new_client
}
}
}
CLIENTS << new_client
pp CLIENTS.size
}