Add 2 crystal LibIPC examples.

tmp
Philippe Pittoli 2023-02-08 09:48:37 +01:00
parent dcc8e7bfd9
commit 4ed4471c18
5 changed files with 126 additions and 0 deletions

6
crystal/.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
/docs/
/lib/
/bin/
/.shards/
*.dwarf
shard.lock

28
crystal/README.md Normal file
View File

@ -0,0 +1,28 @@
# LibIPC examples
Crystal LibIPC examples, using [libipc bindings shard][bindings].
## Installation
```sh
# Compiles all examples.
shards build
```
Currently there are 2 examples:
- pongd (server): repeating every message
- pong (client): sending a message to the pong service and waiting for response
## Usage
```sh
# Run the service
./bin/pongd # run the service
./bin/pong # run the client
```
# LICENCE
ISC
[bindings]: https://git.baguette.netlib.re/Baguette/ipc.cr

23
crystal/shard.yml Normal file
View File

@ -0,0 +1,23 @@
name: libipc-examples
version: 0.1.0
authors:
- Philippe Pittoli <karchnu@karchnu.fr>
description: |
Examples of applications using libipc.
targets:
pong:
main: src/pong.cr
pongd:
main: src/pongd.cr
dependencies:
ipc:
git: https://git.baguette.netlib.re/Baguette/ipc.cr
branch: master
crystal: 1.7.1
license: ISC

39
crystal/src/pong.cr Normal file
View File

@ -0,0 +1,39 @@
require "ipc"
ipc = IPC.new
ipc.timer 5000 # timer event every 5 seconds
fd = ipc.connect "pong" # 'pong' service
# Schedule a message to send to a particular file descriptor
ipc.schedule fd, "Hello this is me!"
ipc.loop do |event|
case event.type
when LibIPC::EventType::MessageRx
m = event.message
if m.nil?
puts "Err, should have received smth :("
exit 1
else
received = String.new(m.to_unsafe, m.size)
puts "msg received: #{received}"
if "Hello this is me!".compare(received) == 0
puts "All good! Goodbye!"
exit 0
end
puts "Received message isn't what was expected!"
exit 1
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
else
puts "Unexpected: #{event.type}"
exit 1
end
end

30
crystal/src/pongd.cr Normal file
View File

@ -0,0 +1,30 @@
require "ipc"
ipc = IPC.new
ipc.timer 5000 # timer event every 5 seconds
fd = ipc.service_init "pong"
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
else
puts "Unexpected: #{event.type}"
exit 1
end
end