Exercise: File server (binary response)

In this exercise you must program a simple file server. The server runs on top of TCP.

Files may have any content text, PDF, JPG images, etc. This means that you cannot read the file line by line (there are no lines in a JPG file).

Protocol design

The protocol is very simple

Error handling: later ...

Getting started: Program the server

The structures of the server is very similar to the Echo TCP server.

However, the service is different - specially the response must be binary (not text oriented).

The following code snippet might be helpful

using (FileStream fileStream = new FileStream(filename, FileMode.Open))
{
    fileStream.CopyTo(stream); 
}

The server should look for the requested files in a special folder set by the server, for example C:/temp

 private static readonly string RootDirectory = "c:/temp";

Client application

Make a simple client application, a console application in a separate Visual Studio solution.

It does not make much sense to show the response on the screen, since it might well be a binary response.
Instead you should write the response into a file - probably with the same name as the file you requested from the file server.

Open the new file to check the the content.

Error handling: File Not Found

If the clients request a file which is unknown to the server, the server must send back a proper response: Some kind of error message.

You must add to the protocol (and the server) to handle File Not Found errors.

The response must have the following structure:

Extra: Socket.SendFile

The class Socket has a method SendFile(filename) which might be helpful.

Socket socket = myClientSocket.Client will give you access to the Socket object, from which you can call the SendFile(filename) method.

Extra: Upload files to the server

Until now the client can request files from the server.

Now you have to add uploading capabilities to the server, so that the client can send files to the server.