crystal unix sockets
This commit is contained in:
parent
630e49571a
commit
e8a079c68c
24
~/Crystal/UNIXSockets/client.cr
Normal file
24
~/Crystal/UNIXSockets/client.cr
Normal 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
|
46
~/Crystal/UNIXSockets/server.cr
Normal file
46
~/Crystal/UNIXSockets/server.cr
Normal 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
|
Loading…
Reference in New Issue
Block a user