C# – Server and Client apps that will send files and other info to each other

cnet

I am trying to do a Server and Client programs, that will communicate with each other, but I can't figure out the best way to do it, so let me explain what I need:

  • The Server app should be able to accept both files and other info (like string arrays, if possible) from the client app.
  • The client app must be able to receive commands from the Server app (like SEND_REPORT, STOP_SELF….)
  • The whole server-client communication should be direct

I have tried using a FTP server for that, but it requires a third party program for that to work (unless I make my Server app a FTP server itself).
So now I am trying to do it with TcpClient and NetworkStream, but I figured out there would be no way to distinguish if the sent info is a file, or a simple string array.

Here is what I have so far, the server side code:

private void handleClient(TcpClient client) {
        NetworkStream stream = client.GetStream();
        stream.WriteByte(1);
        FileStream fileStream = File.Open(le_path, FileMode.Create);
        int read;
        int totalRead = 0;
        byte[] buffer = new byte[1024];
        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) {
            fileStream.Write(buffer, 0, read);
            totalRead += read;
        }
        fileStream.Dispose();
        client.Close();
    }

This code does create a file, but it is bugged, or I don't know, it never leaves the while loop and never goes to Dispose and Close… I can access the file, when I close the program.

Here is the client app code:

client = new TcpClient();
client.Connect(serverIP, serverPort);
byte[] file = File.ReadAllBytes(Constants.TARGET_PATH_LOGS + "squad.jpg");
byte[] fileBuffer = new byte[file.Length];
NetworkStream stream = client.GetStream();
stream.Write(file, 0, fileBuffer.GetLength(0));

So here is what I am asking you:

  • If this is the best way to do it, how can I make the receive code recognizes if it's a file that is sent, or a simple array list data, and how do I make it able to accept any file (meaning to properly get it's name, metadata…)
  • If not, please tell me another way to do what I need.

Best Answer

npinti provides a good example of some code, but in general what you are doing is a very common scenario. The server you are looking to make is a basic web service, often these days using a RESTful API model over HTTP. The client packs up some data in a predefined format of your choosing, and transmits its to a URL of your choosing on the server. The server can send messages to the client using something like WebSockets, which work like simple TCP/IP connections but can pass through most firewalls.

Related Topic