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

47 lines
792 B
Crystal
Raw Permalink Normal View History

2023-06-18 22:07:49 +03:00
require "socket"
require "file_utils"
SOCKET = "/tmp/myapp.sock"
begin
FileUtils.rm(SOCKET)
rescue e : File::NotFoundError
end
server = UNIXServer.new(SOCKET)
CLIENTS = [] of UNIXSocket
Signal::INT.trap do
puts "Closing server..."
server.close(delete = true)
exit
end
def handle_client(client)
loop do
message = client.gets
p! client
if message == "start"
puts "::request START command::"
client.puts "Hello :)"
elsif message == "help"
puts "::request HELP command::"
client.puts "This example ECHO unix server!"
elsif message == "run"
puts "::request RUN command::"
client.puts "Ready, Set, GO!"
else
break
end
end
end
puts "Listen..."
while client = server.accept
spawn handle_client(client)
end