Frage

i am developing an android application that capable of sending file and string (message) to another android device. here i have one server mobile and another as client.

I am really struck with sending file(image) and string using same socket. how to identify whether sending information is file or string.

Please help me on this. the client sends message to server using service and server receives data using ascynctack.

War es hilfreich?

Lösung

I think you have to make a simple protocol to do it.
Example: You will have a struct for a message ( that you send/receive between client & server ) : [message_type][message_length_in_byte][chunked_data][sequence_index][last_sequence]
Where:
- message_type: is a 4 byte integer, it define your message type: ( ex: 0 = message, 1 = send file)
- message_length_in_byte: is a 4 byte integer , it's length of your data in byte.
- chunked_data: your data here, it will have 'message_length_in_byte' bytes to read. Because your data will be very large in some case ( you are going to send a file) so that you have to split your data into many piece of data ( chunked data) . so it's better to define a max value for this field
example: you can set max length of 'chunked_data' per message is: 128, 512,.... bytes or everything you want.
- sequence_index: is a 4 byte integer, because your data will be split into many part/ so this field will let you know the sequence of message
- last_sequence: 1 byte, its value is only 0 or 1 . 0 = your data will have more, the rest of data will send to you later, so you have to read more to get full data. 1 = that mean this is the last data. ( ex: when you send a file, you will split data into many part, and send them in sequence. So when the receiver receive a message with last_sequence = 1,that mean this is the last data of the file, so they will know that you have sent all data of a file). - > That's only idea to do resolve your problem. Thanks

Andere Tipps

This is a general technique not only applicable to Android. Normally you send the information with some header as tip for you how to process it.

E.g. everything you send can be seen as a byte array. The first byte can be used as a "message type" e.g. 0x00 represents string, 0x01 represents image, and so on. If you are unsure about the length of the rest of the message and you need to prepare buffer for it, you can also have the 2 - 5 bytes as an int telling how long this message is. Then you decode the result of the message accordingly.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top