title: TCP push-pull socket server design
body: <p>I am designing a cross-platform messaging service as a learning exercise.  I have programmed socket-based servers before, but always a "client-polls-server" design, like a web server.  I want to be able to target mobile platforms, and I read that polling is a battery drain, so I would like to do push notification.</p>
  
  <p>The server will be TCP-based, written in C++.  What I'm having trouble getting my head around is how to manage the bi-directional nature of the design.  I need a client to be able to send packets to the server as normal, but also listen for packets.  How do I mitigate situations like,  the client is sending data when the server is trying to send to it, or it's blocked listening for data but then needs to send something?</p>
  
  <p>For example, consider the following crude diagram:</p>
  
  <p><img src="https://i.stack.imgur.com/5dLCB.png" alt="crude diagram"></p>
  
  <p>So, let's say client A is in the middle of sending a chunk of data (arrow 1).  While this is happening, client B sends a message (arrow 2), which causes the server to attempt to send data back to client A (arrow 3), but client A hasn't finished sending arrow 1 yet.  What happens in this instance?  Should I setup 2 separate ports on each client, one for inbound, one for outbound?  Do I need to keep track of the state of each connection?</p>
  
  <p>Or is there a better approach to this altogether?</p>