From 4ba5aa93f341917e79f4071d8d0456eb62c0f94c Mon Sep 17 00:00:00 2001 From: Philippe Pittoli Date: Sat, 27 May 2023 22:11:56 +0200 Subject: [PATCH] Add a simple example. --- crystal/src/tcp-unix-to-ipc-unix.cr | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 crystal/src/tcp-unix-to-ipc-unix.cr diff --git a/crystal/src/tcp-unix-to-ipc-unix.cr b/crystal/src/tcp-unix-to-ipc-unix.cr new file mode 100644 index 0000000..134d0ba --- /dev/null +++ b/crystal/src/tcp-unix-to-ipc-unix.cr @@ -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