crystal unix sockets

This commit is contained in:
Alexander Popov 2023-06-18 22:07:49 +03:00
parent 630e49571a
commit e8a079c68c
Signed by: iiiypuk
GPG Key ID: E47FE0AB36CD5ED6
2 changed files with 70 additions and 0 deletions

View File

@ -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

View File

@ -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