I suggest not using (bash) shell scripts as your own messaging server, because bash is too limited to be useful.
read without any parameters reads an entire line before terminating, while its own messaging protocol indicates that the first four bytes determine the length of the next message (in native byte order).
Bash is a terrible binary data processing tool. An improved version of your read command will specify the -n N option to stop reading after N characters (note: not bytes) and -r to remove some processing. For instance. The following will store the first four characters in a variable named var_prefix :
IFS= read -rn 4 var_prefix
Even if you assume that this stores the first four bytes in a variable (it is not!), Then you need to convert the bytes to an integer. Did I mention that bash automatically discards all NUL bytes? These features make bash completely useless for being a fully capable embedded messaging server.
You can deal with this shortcoming by ignoring the first few bytes and start analyzing the result when you find the symbol { , the beginning of the request in JSON format. After that, you should read all the input data until the end of the input is found. You need a JSON parser that stops reading input when it encounters the end of a JSON string. Good luck writing this.
Creating output is simpler, just use echo -n or printf .
Here is a minimal example assuming input ends with } , reads it (without processing), and responds to the result. Although this demo works, I highly recommend not using bash, but a richer (scripting) language like Python or C ++.
source share