snipplets.dev/code/Crystal/UNIXSockets/by_faustinoaq/server.cr

39 lines
643 B
Crystal
Raw Normal View History

2023-06-18 22:08:38 +03:00
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
}