开发者

distinguishable socket input

Im trying to send multiple data items over a tcp socket from an android client to a python server. The user on the client side can make multiple choice开发者_高级运维s so im using a number sent as a character to differentiate between request types. I have to send the choice and specific data depending on the choice.For the current selection (choice no 1 in this case) I need the choice and 2 string fields and an image. I have the image transfer working on its own and the choice working on its own. The problem I am having now is that the buffer reading in the choice is also reading in the byte stream of the image straight after it.


TCP will combine your writes into one packet if they are written before the packet is sent, meaning the information will be received concatenated.

A common solution would be to incorporate an 'opcode' before your data. For example, prefix CHOICE before sending your integer. When you read CHOICE in your python script, you know you are receiving an integer and thus read just that much data. Before you send your image, prefix it with IMG and the number of bytes to read. This way you can read just as many bytes as needed, then look for the next opcode.

Your packet should then look like this:CHOICE1IMG<number of bytes><image bytestream>

Obviously your opcode can be whatever you want, this is just an example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜