0

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.

2 Answers 2

1

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.

0

You need to close the connection stream from your client. The server's while loop will not exit until the client closes the connection.

As for your question regarding how will you know what is your client sending, you could use an initial series of bytes to denote what you are sending. So if you send 0x00, you are sending a file, if you send 0x01, you are sending an array list, and so on.

For the first point, you could do it like so:

using NetworkStream stream = client.GetStream()
    stream.Write(file, 0, fileBuffer.GetLength(0));

For the second, you could try something like so (NOTE: This code is not compiled, but it should point you in the right direction):

byte[] transType = new byte[] {(byte)0};   //Assuming that 0 means you are sending a file.
byte[] file = File.ReadAllBytes(Constants.TARGET_PATH_LOGS + "squad.jpg");
byte[] transData = new byte[transType.Length + file.Length]
transType.CopyTo(transData, 0);

file.CopyTo(transData, tansType.Length);
byte[] fileBuffer = new byte[file.Length];
using NetworkStream stream = client.GetStream()
        stream.Write(file, 0, fileBuffer.GetLength(0));

In your server:

bool isFirst = true;
TransmissionType transmissionType = TransmissionType.Unknown;   //This is an enumeration you can create.

while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) 
{
    if(isFirst) 
    {
        isFirst = false;
        byte transType = buffer[0];
        switch(transType)
        {
            case (byte)0: 
            { 
                transmissionType = TransmissionType.File;
                byte[] bufferToWrite = new byte[buffer.Length - 1];
                Array.Copy(buffer, 1, bufferToWrite, bufferToWrite.Length);
                fileStream.Write(bufferToWrite, 0, read);
                totalRead += read;
                continue;
            }
            ... //Other Cases
        }
    }

    switch(transmissionType)
    {
        case TransmissionType.File :
        {
            fileStream.Write(buffer, 0, read);
            totalRead += read;
            break;
        }
    }                
}
2
  • could you give me example code please, of sending an example file and string array, and how to distinguish it? or at least point me where to read about it
    – Skaidar
    Commented Apr 1, 2015 at 9:24
  • @Skaidar: I have updated my answer. Hope it helps.
    – npinti
    Commented Apr 1, 2015 at 9:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.