How can a client talk to another client using unix domain sockets

.ncnetcatsocatsocketunix-sockets

Using bash we might have something like this with netcat:

nc -lk -U /my/fifo | while read line; do
   # line => {"client_id":123}
done;

clients send data like this:

echo '{"client_id":123,"data":"foo"}' | nc -U /my/fifo

and clients wait for data like this:

echo '{"client_id":123}' | nc -U /my/fifo | while read line; do

done;

my question – how can I send data from one client to another client, without involving all the clients? On the "server", I would need to store a reference to each client, so when I get a message from one client, I know who to forward the message to? How can I store a reference to the clients that are currently connected? Just like websockets, I want to create channels, where anyone registered to that channel will get the message.

Best Answer

So here is the thing, I guess I can respond to clients with:

echo "this is the response" | nc -lk -U /my/fifo

but the whole point is how do I respond differently depending on who the client is? I mean how can you create something very useful if there is no logic based on the client request etc?

My only guess is to have two servers:

nc -lk -U /my/fifo1 | while read line; do

  # custom logic goes here

done > nc -lk -U /my/fifo2

so then clients connect with:

echo '{"client_id":123}' | nc -U /my/fifo1 

nc -U /my/fifo2 | while read line; do

done; 

this betrays what I know about how tcp and unix domain sockets work with Node.js etc, but I guess with bash we have to do it this way?

I also think to avoid race conditions might have to put the above two commands in a single pipe somehow.

Related Question