views:

181

answers:

1

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?

+2  A: 

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:

  • client connects to server
  • server sends contents of a file and terminates the connection
  • client receives contents of a file until the connection is terminated

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:

  • client connects to server
  • server sends number of files that it will transfer (as a 4 byte integer),
  • client receives the number of files that it will receive (as a 4 byte integer),
  • server sends the size of the first file (as a 4 byte integer - but this will limit the max file size to 4GB)
  • client receives the size of the first file
  • server sends contents of the first file
  • client receives the contents of the first file - it reads from the TCP stream exactly the count of bytes as the size of the first file,
  • server sends the size of the second file
  • ....
  • after sending all files, server closes the connection
  • after receiving the last file, client waits for the server to close connection and closes connection

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.

qbeuek