/// <summary>
        /// Initializes a new instance of the <see cref="file_client"/> class.
        /// </summary>
        /// <param name='args'>
        /// The command-line arguments. First ip-adress of the server. Second the filename
        /// </param>
        private file_client(string[] args)
        {
            try
            {
                TcpClient     client = new TcpClient(args[0], PORT);
                NetworkStream stream = client.GetStream();
                Console.WriteLine("Client stream connected");

                LIB.writeTextTCP(stream, args[1]);
                Console.WriteLine("Write " + args[1] + " to server");

                long fileSize = LIB.getFileSizeTCP(stream);
                Console.WriteLine("Get filesize: " + fileSize);

                string fileName = LIB.extractFileName(args[1]); //Hvis en sti indtastes findes filnavnet fra denne.

                if (fileSize > 0)                               //Check if file exists on server, and recieve.
                {
                    receiveFile(AppDomain.CurrentDomain.BaseDirectory + "/" + fileName, stream);
                }
                else
                {
                    Console.WriteLine("File does not exist on server");
                }

                client.GetStream().Close();
                Console.WriteLine("Close stream");
                client.Close();
                Console.WriteLine("Close client");
            }
            catch (System.Net.Sockets.SocketException)
            {
                Console.WriteLine($"Fejl: Kunne ikke oprette forbindelse til {args[0]}, indtast en valid IP adresse.");
            }
        }
Пример #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="file_client"/> class.
        /// </summary>
        /// <param name='args'>
        /// The command-line arguments. First ip-adress of the server. Second the filename
        /// </param>
        private file_client(string[] args)
        {
            // TO DO Your own code
            TcpClient clientSocket = new TcpClient();

            Console.WriteLine(" >> Client connecting");
            clientSocket.Connect(args[0], PORT);
            NetworkStream serverStream = clientSocket.GetStream();

            LIB.writeTextTCP(serverStream, args[1]);

            long size = LIB.getFileSizeTCP(serverStream);

            if (size != 0)
            {
                string fileName = LIB.extractFileName(args[1]);
                receiveFile(fileName, serverStream, size);
            }
            else
            {
                Console.WriteLine(LIB.readTextTCP(serverStream));
            }
            serverStream.Flush();
            clientSocket.Close();
        }
Пример #3
0
        /// <summary>
        /// Receives the file.
        /// </summary>
        /// <param name='fileName'>
        /// File name.
        /// </param>
        /// <param name='io'>
        /// Network stream for reading from the server
        /// </param>
        private void receiveFile(String fileName, NetworkStream io)
        {
            // Adding null terminator to fileName
            LIB.writeTextTCP(io, fileName + "\0");
            long fileSize = LIB.getFileSizeTCP(io);

            // If getting filesize fails, return
            if (fileSize == -1)
            {
                Console.WriteLine("File not found!");
                return;
            }

            byte[] file     = new byte[fileSize];
            int    received = 0;

            // Loop till all files received
            while (received < fileSize)
            {
                if (fileSize - received < BUFSIZE)
                {
                    int lastRead = io.Read(file, received, (int)fileSize - received);
                    received = received + lastRead;
                }
                else
                {
                    int read = io.Read(file, received, BUFSIZE);
                    received = received + read;
                }
            }

            File.WriteAllBytes(LIB.extractFileName(fileName), file);
            Console.WriteLine(LIB.extractFileName(fileName) + " received!");
        }
Пример #4
0
        /// <summary>
        /// Receives the file.
        /// </summary>
        /// <param name='fileName'>
        /// File name.
        /// </param>
        /// <param name='io'>
        /// Network stream for reading from the server
        /// </param>
        private void receiveFile(String filePath, NetworkStream io)
        {
            string fileName      = string.Empty;
            string fileDirectory = string.Empty;
            long   fileSize      = 0;
            int    bytesRead     = 0;

            byte[] buffer = new byte[BUFSIZE];

            //Create directory for file
            fileDirectory = "/root/Desktop/ServerFiles/";
            Directory.CreateDirectory(fileDirectory);

            fileName = LIB.extractFileName(filePath);
            FileStream Fs = new FileStream(fileDirectory + fileName, FileMode.OpenOrCreate, FileAccess.Write);

            Console.WriteLine("Reading file " + fileName + "...");

            //Writes into file as long as it receives bytes, bytesRead>0
            do
            {
                bytesRead = io.Read(buffer, 0, BUFSIZE);
                Fs.Write(buffer, 0, bytesRead);
                Console.WriteLine("Read bytes: " + bytesRead.ToString());
            }while (bytesRead > 0);

            //Lukker fil
            Fs.Close();
        }
Пример #5
0
        /// <param name='fname'>
        /// File name.
        /// </param>
        /// <param name='output'>
        /// Network stream for reading from the server
        /// </param>
        private void receiveFile(String fname, NetworkStream output, long file_size)
        {
            fname = LIB.extractFileName(fname);

            //Opretter mappe og putter ind til denne directory
            string data_directory = "/root/Desktop/TilTorben/";

            Directory.CreateDirectory(data_directory);
            FileStream file = new FileStream(data_directory + fname, FileMode.Create, FileAccess.Write);

            byte[] data = new byte[BUFSIZE];


            int bytes_total = 0;
            int bytes_read;

            Console.WriteLine("Reading file! " + fname);

            //Løkke - der tjekker størrelsen af filen og skriver til bytes read - som læses fra i cw
            while (file_size > bytes_total)
            {
                bytes_read = output.Read(data, 0, data.Length);
                file.Write(data, 0, bytes_read);

                bytes_total += bytes_read;

                Console.WriteLine("Reading bytes = " + bytes_read.ToString() + "\t Total bytes read = " + bytes_total);
            }

            Console.WriteLine("File received");
        }
Пример #6
0
        /// <summary>
        /// Receives the file.
        /// </summary>
        /// <param name='fileName'>
        /// File name.
        /// </param>
        /// <param name='io'>
        /// Network stream for reading from the server
        /// </param>
        private void receiveFile(String fileName, NetworkStream io, long fileSize)
        {
            fileName = LIB.extractFileName(fileName);
            string dataDir = "/root/Desktop/ExFiles/";

            Directory.CreateDirectory(dataDir);
            FileStream file = new FileStream(dataDir + fileName, FileMode.Create, FileAccess.Write);

            byte[] data = new byte[BUFSIZE];             //Vi modtager kun 1k bytes af gangen


            int totalBytes = 0;
            int bytesRead;

            Console.WriteLine("Reading file " + fileName + " ... ");

            //while ((bytesRead = io.Read(data, 0, data.Length)) > 0) //Nu bliver den ved indtil længden af det den modtager er 0
            while (fileSize > totalBytes)
            {
                bytesRead = io.Read(data, 0, data.Length);
                file.Write(data, 0, bytesRead);

                totalBytes += bytesRead;

                Console.WriteLine("Read bytes: " + bytesRead.ToString() + "\t Total bytes read:" + totalBytes);
            }

            Console.WriteLine("File received");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="file_server"/> class.
        /// Opretter en socket.
        /// Venter på en connect fra en klient.
        /// Modtager filnavn
        /// Finder filstørrelsen
        /// Kalder metoden sendFile
        /// Lukker socketen og programmet
        /// </summary>
        private file_server()
        {
            String      clientData   = null;
            IPAddress   localAddress = IPAddress.Any;
            TcpListener serverSocket = new TcpListener(localAddress, PORT);

            serverSocket.Start();

            while (true)
            {
                try
                {
                    Console.WriteLine("Waiting for connection...");

                    TcpClient client = serverSocket.AcceptTcpClient();
                    Console.WriteLine("Client connected!");
                    NetworkStream stream = client.GetStream();
                    Console.WriteLine("Stream created.");

                    clientData = LIB.readTextTCP(stream);
                    Console.WriteLine("Read data from client.");

                    String requestedFile = LIB.extractFileName(clientData);
                    Console.WriteLine("Extracted " + requestedFile + "from client.");

                    //til filer på vilkårlige placeringer
                    long FileLength = LIB.check_File_Exists(clientData);

                    if (FileLength > 0) //tjekker om filen findes på den givne sti
                    {
                        Console.WriteLine($"Fuld sti:{clientData}" +
                                          $"\nstørrelse:{FileLength}");

                        LIB.writeTextTCP(stream, FileLength.ToString()); //sender størrelsen på filen til client
                        SendFile(clientData, stream);
                        Console.WriteLine("File sent.");
                    }
                    else
                    {
                        LIB.writeTextTCP(stream, 0.ToString()); //hvis filen ikke findes skrives der blot 0 til clienten
                    }

                    client.GetStream().Close();
                    Console.WriteLine("Close stream");
                    client.Close();
                    Console.WriteLine("Close client");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
        }
Пример #8
0
        private file_server()
        {
            TcpListener server = null;

            try
            {
                server = new TcpListener(PORT);
                server.Start();
                TcpClient client = null;

                byte[] from    = new byte[BUFSIZE];
                string fileReq = null;

                while (true)
                {
                    Console.WriteLine("Waiting for connection");

                    client = server.AcceptTcpClient();
                    Console.WriteLine("Someone connected");
                    //resetting string for new request.
                    fileReq = null;

                    NetworkStream nStream = client.GetStream();

                    //File request from client
                    fileReq = LIB.readTextTCP(nStream);
                    Console.WriteLine("got: {0}", fileReq);

                    /*Getting filename and then
                     * Checking if file exist on system, els returns 0.*/
                    string file     = LIB.extractFileName(fileReq);
                    long   file_len = LIB.check_File_Exists(file);

                    sendLength(file_len, nStream);
                    if (file_len > 0)
                    {
                        //Delay to ensure nStream is ready.
                        System.Threading.Thread.Sleep(10);
                        sendFile(file, file_len, nStream);
                    }

                    client.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Socket expection: {0}", e);
            }
            finally
            {
                server.Stop();
            }
        }
Пример #9
0
        /// <summary>
        /// The entry point of the program, where the program control starts and ends.
        /// </summary>
        /// <param name='args'>
        /// The command-line arguments.
        /// </param>
        public static void Main(string[] args)
        {
            Console.WriteLine("Server starts...");
            new file_server();
            TcpListener serverSocket = new TcpListener(PORT);

            serverSocket.Start();
            Console.WriteLine("Server socket started");


            while (true)
            {
                try
                {
                    TcpClient clientSocket = serverSocket.AcceptTcpClient();
                    Console.WriteLine("Client acceped");
                    NetworkStream networkStream = clientSocket.GetStream();
                    Console.WriteLine("Got stream");
                    string path = LIB.readTextTCP(networkStream);
                    Console.WriteLine("Path received:" + path);
                    string fileName   = LIB.extractFileName(path);
                    long   fileLength = LIB.check_File_Exists(fileName);
                    Console.WriteLine(fileName);
                    if (fileLength == 0) //File not found
                    {
                        Console.WriteLine("File length: " + fileLength.ToString());
                        LIB.writeTextTCP(networkStream, fileLength.ToString());
                        clientSocket.Close();
                    }
                    else // File found
                    {
                        Console.WriteLine("File length sent: " + fileLength.ToString());
                        LIB.writeTextTCP(networkStream, fileLength.ToString());
                        Thread.Sleep(1);
                        sendFile(path, fileLength, networkStream);
                        clientSocket.Close();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
                finally
                {
                }
            }

            serverSocket.Stop();
            Console.WriteLine(" >> exit");
            Console.ReadLine();
        }
Пример #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="file_client"/> class.
        /// </summary>
        /// <param name='args'>
        /// The command-line arguments. First ip-adress of the server. Second the filename
        /// </param>
        private file_client(string[] args)
        {
            try
            {
                string ipa = args [0];

                IPAddress ipAddress = IPAddress.Parse(ipa);

                TcpClient clientSocket = new TcpClient();

                clientSocket.Connect(ipAddress, PORT);



                NetworkStream serverStream = clientSocket.GetStream();

                // Send filename to server
                string filename = args [1];
                LIB.writeTextTCP(serverStream, filename);

                // Extract filename
                string extractedFilename = LIB.extractFileName(filename);

                // Recieve notice if filename exists
                long currentfilesize = LIB.getFileSizeTCP(serverStream);
                //Console.WriteLine (currentfilesize);

                // If filename exists recieve file
                if (currentfilesize != 0)
                {
                    receiveFile(extractedFilename, serverStream, currentfilesize);
                }
                else
                {
                    Console.WriteLine("Filename: " + extractedFilename + " does not exist");
                }
            }
            catch (ArgumentException e)
            {
                Console.WriteLine("ArgumentException: " + e.Message);
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException: " + se.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
Пример #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="file_server"/> class.
        /// Opretter en socket.
        /// Venter på en connect fra en klient.
        /// Modtager filnavn
        /// Finder filstørrelsen
        /// Kalder metoden sendFile
        /// Lukker socketen og programmet
        /// </summary>
        private file_server()
        {
            TcpListener serverSocket = new TcpListener(IPAddress.Any, PORT);
            TcpClient   clientSocket = default(TcpClient);

            serverSocket.Start();

            byte[] bytes = new byte[BUFSIZE];
            string data;

            while (true)
            {
                clientSocket = serverSocket.AcceptTcpClient();
                Console.WriteLine("Accept conn from client");

                NetworkStream network = clientSocket.GetStream();

                try
                {
                    data = LIB.readTextTCP(network);
                    Console.WriteLine("{0}", data);
                    long fileLength = LIB.check_File_Exists(data);

                    string fileName = LIB.extractFileName(data);

                    Console.WriteLine("File name: {0}", fileName);
                    Console.WriteLine("File length: {0}", fileLength);

                    LIB.writeTextTCP(network, fileLength.ToString());

                    sendFile(data, fileLength, network);

                    Console.WriteLine("Closing connection to client...");
                    Console.WriteLine("Returning to idle.");

                    clientSocket.GetStream().Close();
                    clientSocket.Close();
                }
                catch (FileNotFoundException ex)
                {
                    Console.WriteLine("File not found..!");
                    throw ex;
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Receives the file.
        /// </summary>
        /// <param name='fileName'>
        /// File name.
        /// </param>
        /// <param name='io'>
        /// Network stream for reading from the server
        /// </param>
        private void receiveFile(String fileName, NetworkStream io)
        {
            var fs = new FileStream($"/root/Client/{fileName}", FileMode.OpenOrCreate);

            byte[] inStream = new byte[BUFSIZE];

            int size         = int.Parse(filesize);
            int ReceivedData = 0;
            int DataLeft     = size;

            while (ReceivedData < size)
            {
                int readBytes = io.Read(inStream, 0, BUFSIZE);
                fs.Write(inStream, 0, readBytes);
                ReceivedData += readBytes;
                DataLeft     -= readBytes;
            }
            LIB.extractFileName(fileName);
        }
Пример #13
0
        private void receiveFile(String fileName, NetworkStream io, long fileSize)
        {
            string path = "/root/Desktop/Downloads/" + LIB.extractFileName(fileName);
            int    recievedBytes;

            byte[] data = new byte[fileSize];

            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            int        i  = 0;

            //Getting chunks and write to file based on filesize.
            while (i != (fileSize / 1000) + 1)
            {
                recievedBytes = io.Read(data, 0, data.Length);
                fs.Write(data, 0, recievedBytes);
                i++;
            }
            Console.WriteLine("closing filestream");
            fs.Close();
        }
Пример #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="file_client"/> class.
        /// </summary>
        /// <param name='args'>
        /// The command-line arguments. First ip-adress of the server. Second the filename
        /// </param>
        private file_client(string[] args)
        {
            ClientSocket.Connect(args[0], PORT);
            NetworkStream io = ClientSocket.GetStream();

            LIB.writeTextTCP(io, args[1]);  // Sender fil-sti

            filesize = LIB.readTextTCP(io); // Modtager filesize

            if (filesize == "Kan ikke finde fil")
            {
                Console.WriteLine("File not Found ");
            }
            else
            {
                Console.WriteLine("Receiving file");
                receiveFile(LIB.extractFileName(args[1]), io);
                Console.WriteLine("File received");
                Console.WriteLine($"Filessize is: {filesize}");
            }
        }
Пример #15
0
        private void SetPathAndIP(string[] args)
        {
            if (args[0] != null)
            {
                ServerIP = args[0];
            }
            else
            {
                Console.WriteLine("You need to write IP as first argument");
            }

            if (args[1] != null)
            {
                FilePathServer += args[1];
                FileFromServer  = args[1];
            }
            else
            {
                Console.WriteLine("You need to write server file path as second argument");
            }

            FileFromServer = LIB.extractFileName(FileFromServer);
            FileSavePath  += FileFromServer;
        }
Пример #16
0
        /// <summary>
        /// Receives the file.
        /// </summary>
        /// <param name='fileName'>
        /// File name.
        /// </param>
        /// <param name='io'>
        /// Network stream for reading from the server
        /// </param>
        private void receiveFile(String fileName, NetworkStream io)
        {
            // TO DO Your own code
            string     filename = LIB.extractFileName(fileName);
            long       fileSize = LIB.getFileSizeTCP(io);
            FileStream fs       = new FileStream("/root/Downloads/" + filename, FileMode.Create, FileAccess.Write);

            byte[] recieveBytes = new byte[fileSize];
            int    recieved     = 0;

            if (fileSize == 0)
            {
                Console.WriteLine("File do not exist on server");
                return;
            }
            else
            {
                Console.WriteLine("File size: " + fileSize);
                while (recieved < fileSize)
                {
                    if ((fileSize - recieved) > BUFSIZE)
                    {
                        io.Read(recieveBytes, 0, BUFSIZE);
                        fs.Write(recieveBytes, 0, BUFSIZE);
                        recieved += BUFSIZE;
                    }
                    else
                    {
                        int read = io.Read(recieveBytes, 0, ((int)fileSize - recieved));
                        fs.Write(recieveBytes, 0, read);
                        recieved += read;
                    }
                    Console.WriteLine("Bytes recieved: " + recieved);
                }
            }
        }