petGPS
petGPS copied to clipboard
Reading packet with recv
Hi. I see that you read a packet without any loops with one recv. But afaik it can returns partial data.
I could be wrong, didn’t jump deep into the code.
Hi
That's a fair point, I'm not too good at these network bits. I've never encountered a test where a packet would be "incomplete" so didn't think that could be an issue. Basically the only scenario is when recv() returns an empty packet, the server assumes the client disconnected. How would you better use recv() ? Have it within a loop that starts when the first 2 bytes are the "opening" ones from the device (0x78 0x78) and stops when the last two bytes are the closing ones (0x0D 0x0A), concatenating everything in between ? How would you explain that "partial" packages never happened in my tests (true question, I'm not being sarcastic) ?
Recv returns the actual amount of reading bytes. (Depending on language and library it could work differently). And you could ( in theory) get less than one packet or even more than one. You should work with connection as with a stream, put bytes into a buffer and wait until you get the full packet. Do it in a loop until the connection closed.
It’s about TCP. UDP sockets always return full packets.
In your case packet probably is small enough to be read at once. But it’s no more than a coincidence. One of the worst scenarios - your device sends multiple packets in the same connection, but they stuck somewhere on the internet. Then, when the internet becomes normal you get 9 and 3/4 packets in the first recv() and 1/4 of the last one in the next recv().
I want to use your implementation in my pet tracking service btw ))
It's one of the possible approaches, it could be easily transformed into synchronous code for multithreading. https://github.com/bokolob/tracker/blob/44de2569aae00b01bd907fc4ea680c634c12219d/server/incoming.py#L113