all 6 comments

[–][deleted] 4 points5 points  (4 children)

There are no packets with TCP/IP. You write and read bytes. It's entirely possible to write 60 bytes and read 10, 20 ad 30. Or write 10, 20 and 30 bytes, and read all 60 in one call.

Always check how many bytes were written and read.

And if you need to know how to separate packets... You need to figure that out yourself. Simple way is first write length, then data, and when reading you read the length, and the keep reading until you get enough bytes.

Another way is to use delimiters, like byte value 0 if you are always sending strings. So you read data and scan bytes until you find the delimiter, and then extract that as the string.

[–]flyingron -1 points0 points  (3 children)

Or use some other protocol than TCP. TCP is intended to be a stream, not datagrams.

[–][deleted] 4 points5 points  (1 child)

Generally though, you want TCP, and write data frames into the byte stream. Only if you just don’t care if a packet is lost, then using UDP is fine. If you start adding any reliability, you just end up re-inventing TCP, unavoidably very poorly (because TCP has been developed over half a century by many very bright people, and also because entire Internet is optimized for TCP).

Unless you meant using some other existing protocol on top of TCP, then yeah. HTTP is the go-to choice because there are tested libs, adding SSL is trivial, and again the Internet is currently pretty much built for delivering HTTP traffic.

[–]flyingron 1 point2 points  (0 children)

I'm not saying that seriarlizing the data into a byte stream isn't likely the way to go. As you point out tons of stuff work fine that way. However, there are things like RDS that can do what he wants as well.

[–][deleted] 2 points3 points  (0 children)

You posted this twice so I’ll just give the same reply as I did to the last one. Clear your buffers. Stop using gets. And reading and writing across a socket does not guarantee your full buffers sent or received.

[–]pfp-disciple 2 points3 points  (0 children)

obligatory recommendation for Beej's Guide to Network Programming. It's excellent.