Ejemplo n.º 1
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()
        {
            IPAddress IP     = IPAddress.Parse("10.0.0.1");
            var       Socket = new TcpListener(IP, PORT);

            TcpClient ClientSocket = default(TcpClient);

            Socket.Start();
            Console.WriteLine("SERVER STARTED");

            while (true)
            {
                Console.WriteLine("Waiting for Client");
                ClientSocket = Socket.AcceptTcpClient();
                Console.WriteLine("Client accepted");

                NetworkStream networkStream = ClientSocket.GetStream();

                string filepath = LIB.readTextTCP(networkStream);  // modtager fil-sti
                long   filesize = LIB.check_File_Exists(filepath); // checker fil

                if (filesize != 0)
                {
                    Console.WriteLine("Sending file");
                    LIB.writeTextTCP(networkStream, filesize.ToString()); // sender filesize
                    sendFile(filepath, filesize, networkStream);          // sender fil
                    Console.WriteLine("File sent!");
                }
                else
                {
                    LIB.writeTextTCP(networkStream, "Kan ikke finde fil");
                }
                ClientSocket.Close();
            }
        }
Ejemplo n.º 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();
        }
Ejemplo n.º 3
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();

            clientSocket.Connect(args[0], PORT);

            Console.WriteLine("Client connected...");

            NetworkStream network = clientSocket.GetStream();

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

            fileSize = LIB.getFileSizeTCP(network);
            Console.WriteLine("File size from server: {0}", fileSize, " bytes");

            if (fileSize == 0)
            {
                throw new Exception("File not found..!");
            }
            else
            {
                receiveFile(args[1], network);
                Console.WriteLine("Received file(s)...");
            }
        }
        private void sendFile(String filePath, long fileSize, NetworkStream io)
        {
            LIB.writeTextTCP(io, fileSize.ToString());

            long       length = new System.IO.FileInfo(filePath).Length;
            FileStream fs     = new FileStream(filePath, FileMode.Open);

            byte[] fileBuf = new byte[1000];

            int offset = 0;
            int size   = 1000;

            while (offset < length)
            {
                fs.Read(fileBuf, 0, size);

                io.Write(fileBuf, 0, size);

                offset += 1000;

                if ((offset < length) && (offset + 1000 > length))
                {
                    size = (int)length - offset;
                }
            }

            fs.Close();
        }
Ejemplo n.º 5
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!");
        }
Ejemplo n.º 6
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
            {
                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.");
            }
        }
Ejemplo n.º 7
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)
        {
            TcpClient client = new TcpClient();

            //Sikrer connection til det angivne Port
            client.Connect(args[0], PORT);
            Console.WriteLine($"'{args[0]}' Has been connected <---");

            //Requester client streamet
            NetworkStream server = client.GetStream();

            Console.WriteLine($"'{args[1]}'Filename requested <---");

            string File_Name = args[1];

            LIB.writeTextTCP(server, File_Name);

            long File_Size = LIB.getFileSizeTCP(server);

            //Sædvanlige check om filen eksistere eller ej
            while (File_Size == 0)
            {
                Console.WriteLine("File not found!");
                File_Name = Console.ReadLine();

                Console.WriteLine($"Requesting this file ---> '{File_Name}'");

                LIB.writeTextTCP(server, File_Name);
                File_Size = LIB.getFileSizeTCP(server);
            }

            Console.WriteLine("Size of file ---> " + File_Size);

            receiveFile(File_Name, server, File_Size);
        }
Ejemplo n.º 8
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)
        {
            Console.WriteLine("trying to connect...");

            //etabler tcp forbindelsen
            TcpClient NyTcpSocket = new TcpClient();

            NyTcpSocket.Connect(args [0], PORT);

            //sæt streameren til at snakke på den nu åbne tcp connection
            NetworkStream fileStream = NyTcpSocket.GetStream();

            //Skriv til server at vi ønsker den og den fil.
            LIB.writeTextTCP(fileStream, args [1]);
            //string ModtagetStatus = LIB.readTextTCP (fileStream);
            receiveFile(args [1], fileStream);
            //reager på det der kommer tilbage, hvis det ikke er null.


            // luk forbindelsen.
            fileStream.Close();
            NyTcpSocket.Close();



            // TO DO Your own code
        }
Ejemplo n.º 9
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 = null;
            TcpClient   clientSocket = null;

            try{
                //SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);

                //TcpListener serverSocket = new TcpListener(PORT);
                serverSocket = new TcpListener(IPAddress.Any, PORT);



                clientSocket = default(TcpClient);

                serverSocket.Start();

                while (true)
                {
                    Console.WriteLine(" >> Server Started listening for request");
                    clientSocket = serverSocket.AcceptTcpClient();
                    Console.WriteLine($" Forbindelse til {clientSocket.ToString()}");
                    NetworkStream networkStream = clientSocket.GetStream();
                    //byte[] bytesFrom = new byte[1000];
                    Console.WriteLine((int)clientSocket.ReceiveBufferSize);

                    string dataFromClient = LIB.readTextTCP(networkStream);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));

                    long length = LIB.check_File_Exists(dataFromClient);

                    Console.WriteLine(" >> Data from client - " + dataFromClient);

                    string serverResponse = length.ToString();
                    if (length < 1)
                    {
                        serverResponse = "Filen kunne ikke lokaliseres";
                    }
                    LIB.writeTextTCP(networkStream, serverResponse);
                    Console.WriteLine(" >> " + serverResponse);
                    if (length > 0)
                    {
                        sendFile(dataFromClient, length, networkStream);
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                // Stop listening for new clients.
                clientSocket.Close();
            }
        }
Ejemplo n.º 10
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()
        {
            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;
                }
            }
        }
Ejemplo n.º 11
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)
        {
            LIB.writeTextTCP(io, fileName + "$");
            string lenghtString = LIB.readTextTCP(io);

            long fileSize;

            try
            {
                fileSize = long.Parse(lenghtString);
            }
            catch (System.FormatException)
            {
                Console.WriteLine(lenghtString);
                return;
            }

            if (fileSize < 1)
            {
                Console.WriteLine("Vi er stødt på en fejl. længden er rapporteret som 0 :(");
                return;
            }
            Console.WriteLine("length= " + lenghtString);

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            //https://stackoverflow.com/a/2398471
            using (var fileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.None))
                using (var bw = new BinaryWriter(fileStream))
                {
                    int i;
                    for (i = 0; i < fileSize - 1000; i += 1000)
                    {
                        byte[] bytearray = new byte[1000];
                        io.Read(bytearray, 0, 1000);
                        Console.WriteLine(i.ToString());
                        bw.Write(bytearray);
                        Console.WriteLine($"Wrote: {bytearray[900]}\n");
                    }
                    byte[] lastChunk = new byte[1000];
                    io.Read(lastChunk, 0, 1000);
                    Console.WriteLine(i.ToString());


                    bw.Write(lastChunk, 0, (int)fileSize % 1000);
                    Console.WriteLine($"Wrote: {lastChunk[900]}\n");
                }
        }
Ejemplo n.º 12
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();
        }
Ejemplo n.º 13
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()
        {
            // Create the local endpoint for the socket and the TCP/IP socket
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, PORT);
            Socket     server   = new Socket(SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint
            try
            {
                server.Bind(endPoint);

                // Listen for connections
                server.Listen(10);
                while (true)
                {
                    Console.WriteLine("Listening...");

                    Socket handler = server.Accept();
                    // Create networkstream and connect it to socket
                    NetworkStream networkStream = new NetworkStream(handler);

                    string fileNameAndPath = LIB.readTextTCP(networkStream);
                    Console.WriteLine("Requested file: " + fileNameAndPath);

                    long fileSize = LIB.check_File_Exists(fileNameAndPath);

                    // If file doesnt exist, close the networkstream, shutdown the socket and close it
                    if (fileSize < 1)
                    {
                        Console.WriteLine("File not found!");
                        LIB.writeTextTCP(networkStream, "-1");
                        networkStream.Close();
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                    }
                    else
                    {
                        sendFile(fileNameAndPath, fileSize, networkStream);
                        networkStream.Close();
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                throw;
            }
        }
Ejemplo n.º 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)
        {
            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);
            }
        }
Ejemplo n.º 15
0
        private file_client(string[] args)
        {
            // Setting Path and IP
            SetPathAndIP(args);

            try
            {
                TcpClient client = new TcpClient(ServerIP, PORT);


                // Get a client stream for reading and writing.
                //  Stream stream = client.GetStream();
                NetworkStream stream = client.GetStream();
                Console.WriteLine($"Requesting server for file: {FileFromServer}");



                LIB.writeTextTCP(stream, FilePathServer);

                fileSize = LIB.getFileSizeTCP(stream);


                if (fileSize > 0)
                {
                    Console.WriteLine($"File exists and has size {fileSize}");
                    Console.WriteLine("Saving file...");
                    receiveFile(FileSavePath, stream);
                }

                else
                {
                    Console.WriteLine("File does not exist.");
                }


                client.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }


            // TO DO Your own code
        }
Ejemplo n.º 16
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(new IPAddress(ipAddress), PORT);

            try
            {
                serverSocket.Start();

                while (true)
                {
                    TcpClient newClient = serverSocket.AcceptTcpClient();
                    Console.WriteLine("Client Accepted...");

                    // Recieve filename from client
                    NetworkStream networkStream = newClient.GetStream();
                    String        filename      = LIB.readTextTCP(networkStream);


                    // Check to see if filename exists and notify client
                    long filesize = LIB.check_File_Exists(filename);
                    //Console.WriteLine (filesize);
                    string filesizeascii = filesize.ToString();
                    LIB.writeTextTCP(networkStream, filesizeascii);

                    if (filesize != 0)
                    {
                        sendFile(filename, filesize, networkStream);
                    }

                    newClient.Close();
                }
            }
            catch (ArgumentException e)
            {
                Console.WriteLine("ArgumentException: " + e.Message);
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException: " + se.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally {
                serverSocket.Stop();
            }
        }
Ejemplo n.º 17
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()
        {
            // TO DO Your own code
            TcpListener serverSocket = new TcpListener(localAddr, PORT);

            serverSocket.Start();


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

                    // Accept requests
                    TcpClient client = serverSocket.AcceptTcpClient();
                    Console.WriteLine("Connected to client!");
                    NetworkStream stream = client.GetStream();


                    string fileName = LIB.readTextTCP(stream);
                    Console.WriteLine($"Client asks for file: {fileName}");
                    Console.WriteLine("Cheking if file exists...");

                    long fileSize = LIB.check_File_Exists(fileName);

                    if (fileSize > 0)
                    {
                        Console.WriteLine($"File exists an has size: {fileSize}");
                        LIB.writeTextTCP(stream, fileSize.ToString());
                        sendFile(fileName, fileSize, stream);
                    }
                    else
                    {
                        Console.WriteLine("File does not exist");
                        LIB.writeTextTCP(stream, fileSize.ToString());
                    }

                    client.Close();
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="file_server"/> class.
        /// </summary>
        private file_server()
        {
            // Starts server and accepts a client
            Console.WriteLine("Starting server - waiting for client --->");

            //Opretter en socket
            TcpListener Server_Socket = new TcpListener(IPAddress.Any, PORT);
            TcpClient   Client_Socket = default(TcpClient);

            //Starter serveren og connectecter til client vha Accept funktionen
            Server_Socket.Start();
            Client_Socket = Server_Socket.AcceptTcpClient();

            Console.WriteLine("Connected to client!");

            // getter client stream
            NetworkStream client = Client_Socket.GetStream();

            //Istantiering af filename til at læse og checke om file size eksistere
            string File_Name = LIB.readTextTCP(client);
            long   File_Size = LIB.check_File_Exists(File_Name);

            // loop - der tjekker om filen er fundet.
            while (File_Size == 0)
            {
                string msg = "File '" + File_Name + "' not found";
                Console.WriteLine(msg);

                LIB.writeTextTCP(client, File_Size.ToString());

                File_Name = LIB.readTextTCP(client);
                File_Size = LIB.check_File_Exists(File_Name);
            }

            //Udskriver filnavn og størrelsen som er initialiseret
            Console.WriteLine("Filename: " + File_Name);
            Console.WriteLine("Size: " + File_Size);
            //Skriver texten til client stream
            LIB.writeTextTCP(client, File_Size.ToString());

            sendFile(File_Name, client);

            //Lukker programmet
            Client_Socket.Close();
            Server_Socket.Stop();
        }
Ejemplo n.º 19
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;
                }
            }
        }
Ejemplo n.º 20
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 started");
            clientSocket.Connect(args[0], PORT);
            Console.WriteLine("Server connected");

            NetworkStream networkStream = clientSocket.GetStream();
            string        fileName      = args[1];

            LIB.writeTextTCP(networkStream, fileName);

            receiveFile(fileName, networkStream);

            clientSocket.Close();
            networkStream.Close();
        }
Ejemplo n.º 21
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()
        {
            // TO DO Your own code
            IPAddress   ipAddress    = IPAddress.Parse("10.0.0.1");
            TcpListener serverSocket = new TcpListener(ipAddress, PORT);
            TcpClient   clientSocket = default(TcpClient);

            serverSocket.Start();
            Console.WriteLine(" >> Server Started");
            while (true)
            {
                try
                {
                    clientSocket = serverSocket.AcceptTcpClient();
                    Console.WriteLine(" >> Accept connection from client");
                    NetworkStream networkStream = clientSocket.GetStream();
                    Console.WriteLine(" >> Filename requested from client!");
                    string fileName = LIB.readTextTCP(networkStream);
                    Console.WriteLine($" >> Filename from client: {fileName}");
                    Console.WriteLine(" >> Filesize requested from client!");
                    long fileSize = LIB.check_File_Exists(fileName);
                    Console.WriteLine($" >> Filesize from server: {fileSize}");
                    LIB.writeTextTCP(networkStream, fileSize.ToString());
                    if (fileSize != 0)
                    {
                        Console.WriteLine(" >> Sending file...");
                        sendFile(fileName, fileSize, networkStream);
                        Console.WriteLine(" >> File sent!");
                    }
                    else
                    {
                        LIB.writeTextTCP(networkStream, "File not found");
                        Console.WriteLine(" >> Oops, file not found");
                    }
                    networkStream.Flush();
                    clientSocket.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
Ejemplo n.º 22
0
        private file_client(string[] args)
        {
            Console.WriteLine("Trying to connect...");

            // Opretter forbindelse til Client:
            var client = new TcpClient();

            client.Connect(args[0], PORT);

            // Aktivere stream på den åbne forbindelsen:
            var stream = client.GetStream();

            // Kontakter serveren og angiver hvilken fil:
            LIB.writeTextTCP(stream, args[1]);
            ReceiveFile(args[1], stream);

            stream.Close();
            client.Close();
        }
Ejemplo n.º 23
0
        private file_client(string[] args)
        {
            TcpClient     client  = null;
            NetworkStream nStream = null;

            try
            {
                //Creating connection to server.
                client = new TcpClient(args[0], PORT);
                Console.WriteLine("Connected to server");

                nStream = client.GetStream();

                //Sending file request.
                LIB.writeTextTCP(nStream, args[1]);

                Console.WriteLine("Getting file");

                //Getting filesize.
                long fileSize = getLength(nStream);
                if (fileSize > 0)
                {
                    //Downloading file.
                    receiveFile(args[1], nStream, fileSize);
                }
                else
                {
                    Console.WriteLine("File doesn't exist");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                nStream.Close();
                client.Close();
            }
            Console.WriteLine("Closing socket connection");
            client.Close();
        }
Ejemplo n.º 24
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()
        {                       //initialiser variabler
            string filePath     = string.Empty;
            long   fileSizeLong = 0;
            string fileSizeStr  = string.Empty;

            TcpListener ServerSocket = new TcpListener(PORT);
            TcpClient   ClientSocket = default(TcpClient);

            ServerSocket.Start();
            Console.WriteLine("Server started");
            ClientSocket = ServerSocket.AcceptTcpClient();
            Console.WriteLine("Accepted connection");

            NetworkStream networkStream = ClientSocket.GetStream();

            filePath = LIB.readTextTCP(networkStream);
            Console.WriteLine("The client wants " + filePath);

            //Gets file size, and checks whether it exists
            fileSizeLong = LIB.check_File_Exists(filePath);
            fileSizeStr  = fileSizeLong.ToString();                     //converts it to string
            LIB.writeTextTCP(networkStream, fileSizeStr);               // sending the size of the file to client

            while (fileSizeLong == 0)
            {
                Console.WriteLine("Error, file does not exist");
                filePath = LIB.readTextTCP(networkStream);
                Console.WriteLine(filePath);

                //Gets file size, and checks whether it exists
                fileSizeLong = LIB.check_File_Exists(filePath);
                fileSizeStr  = fileSizeLong.ToString();
                LIB.writeTextTCP(networkStream, fileSizeStr);
            }

            Console.WriteLine("The size of the file is {0} bytes", fileSizeLong);
            sendFile(filePath, fileSizeLong, networkStream);              //kalder sendFile funktionen

            ClientSocket.Close();
            ServerSocket.Stop();
        }
Ejemplo n.º 25
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)
        {
            //If file does not exist on the server, the user can input another filename. Won't continue untill a correct name is input
            long fileSize = 0;

            do
            {
                LIB.writeTextTCP(io, fileName);                 //Sends filename to server
                fileSize = LIB.getFileSizeTCP(io);              //Reads filesize from server

                //If file does not exist, get new filename
                if (fileSize == 0)
                {
                    Console.WriteLine("File does not exist, write filename:");
                    fileName = Console.ReadLine();
                }
            } while(fileSize == 0);


            Console.WriteLine("Filesize: " + fileSize);

            string dataDir = "/root/ExFiles/";                                                             //filepath to save file to

            Directory.CreateDirectory(dataDir);                                                            //Create directory if it does not exist
            FileStream fileStream = new FileStream(dataDir + fileName, FileMode.Create, FileAccess.Write); //Creates file and return filestream
            var        fileBuffer = new byte [BUFSIZE];                                                    //Buffer for holding filedata packets

            Console.WriteLine("Reading...");

            int bytesRead      = 0;
            int totalBytesRead = 0;

            while (totalBytesRead < fileSize)
            {
                bytesRead = io.Read(fileBuffer, 0, BUFSIZE);
                fileStream.Write(fileBuffer, 0, bytesRead);
                totalBytesRead += bytesRead;
            }

            Console.WriteLine("Done reading");
            fileStream.Close();
        }
Ejemplo n.º 26
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()
        {
            // TO DO Your own code

            TcpListener serverSocket = new TcpListener(IPAddress.Any, PORT);

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


            while (true)
            {
                try
                {
                    TcpClient clientSocket = serverSocket.AcceptTcpClient();
                    Console.WriteLine("Accept connection from client");
                    NetworkStream networkStream = clientSocket.GetStream();
                    string        fileName      = LIB.readTextTCP(networkStream);
                    long          fileSize      = LIB.check_File_Exists(fileName);

                    if (fileSize == 0)
                    {
                        Console.WriteLine("File does not exist");
                    }
                    else
                    {
                        LIB.writeTextTCP(networkStream, fileSize.ToString());

                        sendFile(fileName, fileSize, networkStream);

                        Console.WriteLine("File send");
                    }

                    clientSocket.Close();
                    networkStream.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }
Ejemplo n.º 27
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(PORT);
            TcpClient   clientSocket = default(TcpClient);

            serverSocket.Start();

            while (running)
            {
                requestCount++;
                string returnText = LIB.readTextTCP(clientSocket.GetStream());
                long   fileSize   = LIB.check_File_Exists(returnText);
                if (fileSize != 0)
                {
                    LIB.writeTextTCP(clientSocket.GetStream(), fileSize.ToString());
                }
            }
            serverSocket.Stop();
            clientSocket.Close();
        }
Ejemplo n.º 28
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}");
            }
        }
Ejemplo n.º 29
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(new IPEndPoint(IPAddress.Any, PORT));
            TcpClient   clientSocket = default(TcpClient);

            serverSocket.Start();
            Console.WriteLine(" >> Server Started");


            while (true)
            {
                try
                {
                    clientSocket = serverSocket.AcceptTcpClient();
                    NetworkStream networkStream  = clientSocket.GetStream();
                    string        dataFromClient = LIB.readTextTCP(networkStream);
                    Console.WriteLine(" >> Data from client - " + dataFromClient);
                    if (LIB.check_File_Exists(dataFromClient) != 0)
                    {
                        FileInfo fileInfo = new FileInfo(dataFromClient);
                        long     fileSize = fileInfo.Length;
                        LIB.writeTextTCP(networkStream, fileSize.ToString());

                        sendFile(dataFromClient, fileSize, networkStream);
                    }
                    else
                    {
                        LIB.writeTextTCP(networkStream, "" + 0);
                    }

                    networkStream.Flush();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            clientSocket.Close();
            serverSocket.Stop();
        }
Ejemplo n.º 30
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)
        {
            string filePath = "";
            long   fileSize = 0;

            TcpClient ClientSocket = new TcpClient();

            try
            {
                ClientSocket.Connect(args[0], PORT);
                Console.WriteLine("Connected to {0}, port {1}", args[0], PORT);
            }
            catch
            {
                Console.WriteLine("No connection");
            }
            NetworkStream serverStream = ClientSocket.GetStream();

            //Saving requested file in variable filePath
            filePath = args[1];
            Console.WriteLine("Requesting file...");
            LIB.writeTextTCP(serverStream, filePath);

            fileSize = LIB.getFileSizeTCP(serverStream);

            //If file does not exist, keep asking for existing file
            while (fileSize == 0)
            {
                Console.WriteLine("!File not found!");
                Console.WriteLine("Enter new file: ");
                filePath = Console.ReadLine();

                Console.WriteLine("Requesting file...");
                LIB.writeTextTCP(serverStream, filePath);
                fileSize = LIB.getFileSizeTCP(serverStream);
            }
            Console.WriteLine("Receiving file...");
            receiveFile(filePath, serverStream);
        }