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.