Fixed a bug where a socket could be mistakenly discarded

Added some robustness to sending data over socket