Add a simple example.

tmp
Philippe Pittoli 2023-05-27 22:11:56 +02:00
parent 556bdb58dd
commit 4ba5aa93f3
1 changed files with 51 additions and 0 deletions

View File

@ -0,0 +1,51 @@
# WARNING: This code is for DEBUG only.
# Listen to a UNIX socket, connect to another one.
require "ipc"
ipc = IPC.new
ipc.timer 5000 # timer event every 5 seconds
fd = ipc.connect "pong" # 'pong' service
ipc.loop do |event|
case event.type
when LibIPC::EventType::MessageRx
m = event.message
if m.nil?
puts "No message"
else
received = String.new(m.to_unsafe, m.size)
pp! received
ipc.schedule event.fd, m, m.size
end
when LibIPC::EventType::MessageTx
puts "A message has been sent"
when LibIPC::EventType::Connection
puts "A client just connected #JOY"
when LibIPC::EventType::Disconnection
puts "A client just disconnected #SAD"
when LibIPC::EventType::Timer
STDOUT.write "\rTimer!".to_slice
when LibIPC::EventType::External
else
puts "Unexpected: #{event.type}"
exit 1
end
end
# Read an IPC network packet and remove the first 4 bytes.
buffer = Bytes.new 1_000_000
while true
len = STDIN.read buffer
break if len == 0
STDOUT.write buffer[4.. len -1]
end
# Input to IPC network packets.
buffer = Bytes.new 1_000_000
while true
len = STDIN.read buffer
break if len == 0
STDOUT.write_bytes len, IO::ByteFormat::BigEndian
STDOUT.write buffer[0.. len -1]
end