Reputation: 3159
I've recently knocked up a server/client app for Windows & Android that allows one to send a file from Windows to an android phone over a socket connection.
It works great for a single file but trying to send multiple files over in a single stream is causing me problems. I've also realised that aside from the binary data, I will need to send messages over the socket to indicate error states and other application messages. I have little experience with network programming and and wondering what is the best way forward.
Basically the C# server side of the app just goes into a listening state and uses Socket.SendFile to transmit the file. On Android I use the standard Java Socket.getInputStream() to receive the file. That works great for a single file transfer, but how should I handle multiple files and error/messaging information? Do I need to use a different socket for each file? Should I be using a higher level framework to handle this or can I send everything over the single socket? Any other suggestions for frameworks or learning materials?
Upvotes: 2
Views: 2238
Reputation: 4206
Basically you have to define some kind of data transfer protocol. You can try to find an existing protocol or define your own. Right now your protocol is defined like this:
Communicating through TCP sockets means that generally you have to treat the connection as a two way stream of bytes. The best way to design a protocol is to make it describe the things that are going to be sent, so that the receiving side knows what to expect.
To solve your problem, your protocol could look something like this:
You can enrich this simple protocol with sending file names (preceded with file name lengths) or some confirmation or error codes. You can send the file contents in n-bytes chunks with a checksum after each chunk, which the client must verify. Your imagination is the only limit.
Upvotes: 4