crystal unix sockets by faustinoaq
This commit is contained in:
parent
e8a079c68c
commit
fed19bda4c
28
~/Crystal/UNIXSockets/by_faustinoaq/client.cr
Normal file
28
~/Crystal/UNIXSockets/by_faustinoaq/client.cr
Normal 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}"
|
||||
}
|
1
~/Crystal/UNIXSockets/by_faustinoaq/link.txt
Normal file
1
~/Crystal/UNIXSockets/by_faustinoaq/link.txt
Normal file
@ -0,0 +1 @@
|
||||
https://github.com/crystal-lang/crystal/issues/4277#issuecomment-294009173
|
38
~/Crystal/UNIXSockets/by_faustinoaq/server.cr
Normal file
38
~/Crystal/UNIXSockets/by_faustinoaq/server.cr
Normal 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
|
||||
}
|
Loading…
Reference in New Issue
Block a user