crystal unix sockets by faustinoaq

This commit is contained in:
Alexander Popov 2023-06-18 22:08:38 +03:00
parent e8a079c68c
commit fed19bda4c
Signed by: iiiypuk
GPG Key ID: E47FE0AB36CD5ED6
3 changed files with 67 additions and 0 deletions

View File

@ -0,0 +1,28 @@
require "socket"
client = UNIXSocket.new("/tmp/myapp.sock")
Signal::INT.trap {
client.puts "quit"
exit
}
print "name: "
name = gets.to_s
spawn {
loop {
msg = client.gets
if msg
puts msg
else
puts "server closed"
exit
end
}
}
loop {
msg = gets.to_s
client.puts "#{name}: #{msg}"
}

View File

@ -0,0 +1 @@
https://github.com/crystal-lang/crystal/issues/4277#issuecomment-294009173

View File

@ -0,0 +1,38 @@
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
}