How to approach socket programming between C # & # 8594; Java (Android)
I recently kicked out a Windows and Android server / client app that allows you to send a file from Windows to an Android phone over a socket connection.
It works fine for a single file, but trying to send multiple files in the same stream is giving me problems. I also realized that in addition to binary data, I would need to send messages over a socket to indicate error states and other application messages. I have little experience with network programming and I think this is the best way forward.
Basically the C # server side of the application just goes into listening state and uses Socket.SendFile to transfer the file. On Android I am using standard Java Socket.getInputStream () to get the file. This works great for transferring a single file, but how should I handle multiple files and error / message information? Do I need to use a different socket for each file? Should I use a higher level framework to handle this, or can I send everything over a single socket? Any other suggestions for basics or tutorials?
a source to share
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
- the server sends the file content and terminates the connection
- the client receives the contents of the file until the connection is complete
Communication over TCP sockets means that generally you should treat the connection as a two-way stream of bytes. The best way to design a protocol is to describe what will be sent so that the receiving party knows what to expect.
To solve your problem, your protocol might look something like this:
- client connects to server
- the server sends the number of files it will transfer (as a 4-byte integer),
- the client receives the number of files it will receive (as a 4-byte integer),
- the server sends the size of the first file (as an integer of 4 bytes), but this will limit the maximum file size to 4 GB.
- client gets the size of the first file
- the server sends the contents of the first file
- the client receives the contents of the first file - it reads from the TCP stream exactly the number of bytes as the size of the first file,
- the server sends the size of the second file
- ....
- after sending all files, the server closes the connection
- after receiving the last file, the client waits for the server to close the connection and close the connection.
You can enrich this simple protocol by sending filenames (with long filenames) or some confirmation or error codes. You can send the contents of a file in n-byte chunks with a checksum after each chunk the client needs to check. Your imagination is the only limit.
a source to share