I’m working with asyn sockets now. I have a callback function ‘onDataReceived’, which is triggered whenever I receive any data.
First I was getting a single char at a time, so I changed socketPacket data buffer to a big array. Now when ever I receive data, I get it all at once, but when I try to send a bigger file, it doesn’t work once it exceeds the array size.
My question is this. I have a multithreaded socket server. How can I determinate whenever all data is received? for example I need to send an image, I encode the image into base64 and contruct a command “BASE64IMAGE” and then server reads the string until it reaches END_OF_DATA? is there a better way to do it? thanks!
There are three standard options for sending a “message” (whether that’s an image or whatever – a whole blob of data which may be large):
Personally, I like the last option – it makes reading the data and being sure that you’ve got it all much simpler than the first two options. You can allocate the right amount of memory to receive the data before you start, etc. However, it doesn’t cope well when you don’t know the message size before you start. You can modify the scheme by having multiple “chunks” for a single message, where you send the chunk size then the data, and a chunk size of 0 indicates the end of the data.
Note that if you’re transferring data over just a socket, and you don’t need it to be 7-bit clean ASCII, I wouldn’t convert to Base-64 first. Just transfer it as binary data – your code will be simpler and more efficient both in time and bandwidth.