0

I currently have a program that listens and sends on a TCP socket.

The problem I'm having is that I send a packet and sometimes it breaks into pieces. So my listening TCP socket class thinks the first piece that comes in is the entire payload.

What is the typical approach people take when programming with TCP connections?

stackoverflow
  • 18,348
  • 50
  • 129
  • 196
  • 3
    TCP is a *stream-oriented* protocol. You shouldn't be thinking in terms of packets. See http://stackoverflow.com/questions/14745716 for a similar question I answered this morning. – Jon Skeet Feb 07 '13 at 22:16
  • How about sending some code string after sending the object that assures that complete object is received? – Ravindra Gullapalli Feb 07 '13 at 22:17
  • @JonSkeet ok well if I sent a (we'll say) header which tells how long the 'stream' is. How can we even be sure that our 'header' comes through in one piece. My Server should have no knowledge to how big my stream coming in is. So my client needs to tell it. – stackoverflow Feb 07 '13 at 22:36
  • 3
    @Mrshll187: You can't - but you'd usually know how long it was. (For example, you'd always send four bytes for a 32-bit length.) You could keep reading until you'd read all four bytes, at which point you'd know how much other data you need to read for the message. – Jon Skeet Feb 07 '13 at 22:37
  • @JonSkeet A coworker just placed your book on my desk. Small world. Thanks again for your resposne – stackoverflow Feb 18 '13 at 18:08

1 Answers1

2

You cannot assume that the first piece is the entire payload. You have to keep reading off the socket until you get all of it.

There are two options:

Option 1
Mark the end of your messages (data structures). Your listener then keeps reading until it gets the end-of-message marker.

Option 2
Send the length of you message or data structure before you send the actual data. Your listener then keeps reading until its read all the bytes.

Jay
  • 9,314
  • 7
  • 33
  • 40
  • 2
    You should prefer option 2 unless you can be sure your data cannot under any circumstances contain the end of message marker. – mpartel Feb 07 '13 at 22:51
  • 1
    If the data needs to contain the marker, it can be escaped. Its not a big deal. – Jay Feb 07 '13 at 22:56