diff --git a/~/Crystal/UNIXSockets/client.cr b/~/Crystal/UNIXSockets/client.cr new file mode 100644 index 0000000..d8b314b --- /dev/null +++ b/~/Crystal/UNIXSockets/client.cr @@ -0,0 +1,24 @@ +require "socket" + +# connect to socket +sock = UNIXSocket.new("/tmp/myapp.sock") + +loop do + print "Enter command [help, start, run]: " + + # get string from terminal input + string = gets.not_nil!.to_s + + if string == "q" + break + end + + # send string to server + sock.puts "#{string}\n" + + # get response from server & print + response = sock.gets + puts response +end + +sock.close diff --git a/~/Crystal/UNIXSockets/server.cr b/~/Crystal/UNIXSockets/server.cr new file mode 100644 index 0000000..fd5a7f4 --- /dev/null +++ b/~/Crystal/UNIXSockets/server.cr @@ -0,0 +1,46 @@ +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