The main problem, I think, is that you have too much code. (If it's too big to post here, it's too big to ask strangers to debug for you.)
For example, there's a whole lot of code in your post which doesn't have anything to do with sending data through sockets. Take all of that code and delete it. In fact, frankly, I could be wrong but I don't see anything there which sends data through a socket, so perhaps you're looking at the wrong code.
Anyway once you get through deleting all the code which is irrelevant to the problem,
you should end up with fewer than 50 lines of executable code. It's also possible that once you have done that then the problem won't exist any more. If that's the case then put back the deleted code one piece at a time until the problem starts to happen again, at which time you know the code you just added is causing the problem.