Fix for truncated messages being received
Code cleanup and flush stdout after writing message