Exemplo n.º 1
0
        public async Task ClientSend(NetworkStream networkStream, ServerClientMsg objectToClient)
        {
            var xmlSerializer = new XmlSerializer(objectToClient.GetType());

            StringBuilder SerializedSb = new StringBuilder();

            using (var stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, objectToClient);
                SerializedSb.Append(stringWriter.ToString());
            }

            var serializedString = SerializedSb.ToString();
            var MsgToSend        = Encoding.UTF8.GetBytes(serializedString);
            await networkStream.WriteAsync(MsgToSend, 0, MsgToSend.Length);
        }
Exemplo n.º 2
0
        public async Task <ServerClientMsg> ClientReceive(NetworkStream networkStream)
        {
            var             ReadBytes      = new byte[8192];
            ServerClientMsg ReceivedObject = new ServerClientMsg();

            int BytesRead = await networkStream.ReadAsync(ReadBytes, 0, ReadBytes.Length);

            if (BytesRead > 0)
            {
                ClientSb.Append(Encoding.UTF8.GetString(ReadBytes, 0, BytesRead));
                var ReceivedMsg = ClientSb.ToString();
                if (ReceivedMsg.IndexOf("</TcpMsg>") > -1)
                {
                    XmlSerializer xmlS = new XmlSerializer(typeof(ServerClientMsg));
                    using (var stringReader = new StringReader(ReceivedMsg))
                    {
                        ReceivedObject = (ServerClientMsg)xmlS.Deserialize(stringReader);
                    }
                    ClientSb.Clear();
                }
            }
            return(ReceivedObject);
        }
Exemplo n.º 3
0
        private async Task OnTransferAsync(TcpClient tcpClient, StateObject tcpState)
        {
            await Task.Yield();

            using (var networkStream = tcpClient.GetStream())
            {
                var buffer = new byte[8192];

                // Receiving and deserialized the serializable object
                var byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);

                if (byteCount > 0)
                {
                    ServerSb.Append(Encoding.UTF8.GetString(buffer, 0, byteCount));
                    var StringMsg = ServerSb.ToString();
                    if (StringMsg.IndexOf("</TcpMsg>") > -1)
                    {
                        var xmlSerializer     = new XmlSerializer(typeof(ServerClientMsg));
                        var ReceivedMsgObject = new ServerClientMsg();
                        using (var textReader = new StringReader(StringMsg))
                        {
                            ReceivedMsgObject = (ServerClientMsg)xmlSerializer.Deserialize(textReader);
                        }

                        // Clear string builder since we are done with it
                        ServerSb.Clear();

                        var MsgObjectToReturn = new ServerClientMsg();

                        // If this thread is for the server
                        if (tcpState.ClientType == false)
                        {
                            MsgObjectToReturn = ServerCreateRly(ReceivedMsgObject);
                        }
                        // If this thread if for the client
                        else
                        {
                            // Now that we have the serializable object, we need to switch through all the commands
                            switch (ReceivedMsgObject.Command)
                            {
                            // Data request command
                            case (int)ServerClientMsg.Commands.DataRq:

                                byte[] file;
                                string hash = string.Empty;
                                //Console.WriteLine("Client Server: received data request for file: {0} segment: {1}", ReceivedMsgObject.NameOfFile,ReceivedMsgObject.SegmentOfFile);

                                string filepath = tcpState.TempFolderPath + @"/" + Path.GetFileNameWithoutExtension(ReceivedMsgObject.NameOfFile);
                                filepath += "_temp" + ReceivedMsgObject.SegmentOfFile + Path.GetExtension(ReceivedMsgObject.NameOfFile);
                                //Console.WriteLine("Client Server: Retreiving file: {0}", filepath);

                                // See if the client's server actually has the file or not
                                if (File.Exists(filepath))
                                {
                                    file = File.ReadAllBytes(filepath);
                                }
                                else
                                {
                                    //Console.WriteLine("Client Server could not find the file {0}", filepath);
                                    file = new byte[2];
                                }

                                // Retrieveing the hash to send back with the data segment
                                foreach (var pair in tcpState.FileDict)
                                {
                                    if (pair.Key == ReceivedMsgObject.NameOfFile)
                                    {
                                        ObjectForFiledict obj = pair.Value;
                                        hash = obj.Hash;
                                        //Console.WriteLine("Client Server: Hash = {0}", hash);
                                        break;
                                    }
                                }

                                MsgObjectToReturn.DataRly(hash, ReceivedMsgObject.SegmentOfFile, file);

                                break;

                            default:
                                Console.WriteLine("Invalid command to the client server");
                                break;
                            }
                        }

                        // At this point, the serializable object should be popululated with the proper command and info
                        StringBuilder SerializedSb = new StringBuilder();

                        using (var stringWriter = new StringWriter())
                        {
                            xmlSerializer.Serialize(stringWriter, MsgObjectToReturn);
                            SerializedSb.Append(stringWriter.ToString());
                        }

                        var serializedString = SerializedSb.ToString();
                        var MsgToSend        = Encoding.UTF8.GetBytes(serializedString);

                        // Sending the serializable response back
                        await networkStream.WriteAsync(MsgToSend, 0, MsgToSend.Length);

                        //Console.WriteLine("[Server] Response has been given");
                    }
                }
            }
        }
Exemplo n.º 4
0
        public ServerClientMsg ServerCreateRly(ServerClientMsg ReceivedMsgObject)
        {
            var MsgObjectToReturn = new ServerClientMsg();

            switch (ReceivedMsgObject.Command)
            {
            // If we received a Register Files message from the client
            case (int)ServerClientMsg.Commands.RegisterRq:
                List <bool> SuccessList = new List <bool>();
                // Looping through all the messages and add it to the dictionary if possible
                for (int i = 0; i < ReceivedMsgObject.Files.Count; i++)
                {
                    if (!ServerDict.ContainsKey(ReceivedMsgObject.Files[i]))
                    {
                        ServerDataObject Sdo = new ServerDataObject();
                        // Store each success and failure in a list for a message back to the client
                        SuccessList.Add(Sdo.AddEndPoint(ReceivedMsgObject.ClientIP, ReceivedMsgObject.ClientPort));
                        Sdo.Length = ReceivedMsgObject.FilesLength[i];
                        ServerDict.Add(ReceivedMsgObject.Files[i], Sdo);
                        Console.WriteLine("Server: Added file: {0} to the server dict for client: {1} , {2}", ReceivedMsgObject.Files[i],
                                          ReceivedMsgObject.ClientIP, ReceivedMsgObject.ClientPort);
                    }
                    else
                    {
                        bool successflag = true;
                        foreach (var pair in ServerDict)
                        {
                            if (pair.Key == ReceivedMsgObject.Files[i])
                            {
                                ServerDataObject ServObj = pair.Value;
                                for (int k = 0; k < ServObj.Addresses.Count; k++)
                                {
                                    if (ServObj.Ports[k] == ReceivedMsgObject.ClientPort)
                                    {
                                        if (ServObj.Addresses[k] == ReceivedMsgObject.ClientIP)
                                        {
                                            Console.WriteLine("Server: Reject file {0} reg for client: {1} , {2}", ReceivedMsgObject.Files[i],
                                                              ReceivedMsgObject.ClientIP, ReceivedMsgObject.ClientPort);
                                            successflag = false;
                                        }
                                    }
                                }
                                if (successflag == true)
                                {
                                    Console.WriteLine("Server: Added client {0} , {1} to server dict",
                                                      ReceivedMsgObject.ClientIP, ReceivedMsgObject.ClientPort, ReceivedMsgObject.Files[i]);
                                    ServObj.AddEndPoint(ReceivedMsgObject.ClientIP, ReceivedMsgObject.ClientPort);
                                }
                                break;
                            }
                        }

                        SuccessList.Add(successflag);
                    }
                }
                // Compile the return message for the client
                MsgObjectToReturn.RegisterRly(SuccessList);

                break;

            // If we received a file list request from the client
            case (int)ServerClientMsg.Commands.FileListRq:

                // For a fileName list and a file size list
                List <string> fileName = new List <string>();
                List <long>   fileSize = new List <long>();

                foreach (var pair in ServerDict)
                {
                    bool             HasFileAlready = false;
                    ServerDataObject ServObj        = pair.Value;
                    for (int k = 0; k < ServObj.Addresses.Count; k++)
                    {
                        if (ServObj.Ports[k] == ReceivedMsgObject.ClientPort)
                        {
                            if (ServObj.Addresses[k] == ReceivedMsgObject.ClientIP)
                            {
                                Console.WriteLine("Server: client {0} , {1} already has the file {2}", ReceivedMsgObject.ClientIP,
                                                  ReceivedMsgObject.ClientPort, pair.Key);
                                HasFileAlready = true;
                                break;
                            }
                        }
                    }
                    if (HasFileAlready == false)
                    {
                        fileName.Add(pair.Key);
                        ServerDataObject obj = pair.Value;
                        fileSize.Add(obj.Length);
                    }
                }
                MsgObjectToReturn.FileListRly(fileName, fileSize);
                break;

            // If we received a file location request from the client
            case (int)ServerClientMsg.Commands.FileLocRq:

                // For a fileName list and a file size list
                List <string> addresses = new List <string>();
                List <int>    ports     = new List <int>();
                long          length    = 0;

                foreach (var pair in ServerDict)
                {
                    if (pair.Key == ReceivedMsgObject.NameOfFile)
                    {
                        ServerDataObject SObj = pair.Value;
                        addresses = SObj.Addresses;
                        ports     = SObj.Ports;
                        length    = SObj.Length;
                    }
                }

                MsgObjectToReturn.FileLocRly(length, addresses, ports);


                break;

            // On leave request, the server need to remove all files that has the client's ip address.
            // if the client is the last address that is associated with that file, then the server needs to remove the file
            case (int)ServerClientMsg.Commands.LeaveRq:

                List <string> FilestoRemove = new List <string>();

                foreach (var pair in ServerDict)
                {
                    List <int> indexToRemove = new List <int>();

                    ServerDataObject objOfFile = pair.Value;
                    for (int i = 0; i < objOfFile.Addresses.Count; i++)
                    {
                        if (objOfFile.Addresses[i] == ReceivedMsgObject.ClientIP)
                        {
                            if (objOfFile.Ports[i] == ReceivedMsgObject.ClientPort)
                            {
                                indexToRemove.Add(i);
                            }
                        }
                    }
                    // This allows the removal process to be skipped if the client doesn't have this file
                    if (indexToRemove.Any())
                    {
                        foreach (var index in indexToRemove)
                        {
                            objOfFile.Addresses.RemoveAt(index);
                            objOfFile.Ports.RemoveAt(index);
                        }
                        if (!objOfFile.Addresses.Any())
                        {
                            FilestoRemove.Add(pair.Key);
                        }
                    }
                }

                // Now the server has to remove all the files that doesn't have any clients on it
                if (FilestoRemove.Any())
                {
                    foreach (var key in FilestoRemove)
                    {
                        ServerDict.Remove(key);
                    }
                }


                MsgObjectToReturn.LeaveRly();
                break;

            case (int)ServerClientMsg.Commands.DataRly:
                Console.WriteLine("Requesting Data from server instead of client");
                break;

            default:
                break;
            }
            return(MsgObjectToReturn);
        }
Exemplo n.º 5
0
        private async Task ClientOnTransferAsync(TcpClient tcpclient, ClientPassableObject taskObject)
        {
            await Task.Yield();

            using (var networkStream = tcpclient.GetStream())
            {
                var objectToClient = new ServerClientMsg();
                // send the proper serializable message depending on the command that was given
                switch (taskObject.command)
                {
                case (int)ClientPassableObject.enCommands.RegFiles:
                    objectToClient.RegisterRq(taskObject.address, taskObject.port, taskObject.FilesToReg, taskObject.FilesLength);
                    break;

                case (int)ClientPassableObject.enCommands.PrintDownloadable:
                    objectToClient.FileListRq(taskObject.address, taskObject.port);
                    break;

                case (int)ClientPassableObject.enCommands.Leave:
                    objectToClient.LeaveRq(taskObject.address, taskObject.port);
                    break;

                case (int)ClientPassableObject.enCommands.FileLocation:
                    objectToClient.FileLocRq(taskObject.FileToDownload);
                    break;

                case (int)ClientPassableObject.enCommands.GetFile:
                    objectToClient.DataRq(taskObject.FileToDownload, taskObject.FileSegmentToDownload);
                    break;
                }
                await ClientSend(networkStream, objectToClient);

                // Start receiving reply from the server
                ServerClientMsg ReceivedObject = await ClientReceive(networkStream);

                switch (ReceivedObject.Command)
                {
                // If it is a Register file reply then tell the user which file was successful.
                case (int)ServerClientMsg.Commands.RegisterRly:
                    Console.WriteLine("");
                    for (int i = 0; i < taskObject.FilesLength.Count; i++)
                    {
                        if (ReceivedObject.SuccessCount[i] == true)
                        {
                            Console.WriteLine("You have successfully registered file: {0}", Path.GetFileName(taskObject.FilesToReg[i]));
                        }
                        else
                        {
                            Console.WriteLine("You were not able to registered file: {0}", Path.GetFileName(taskObject.FilesToReg[i]));
                        }
                    }
                    taskObject.FilesRegSuccessCount = ReceivedObject.SuccessCount;

                    taskObject.DoneFlag = true;

                    break;

                // if it is a file list request then we need to print it all on the screen
                case (int)ServerClientMsg.Commands.FileListRly:

                    // if the server did not return anything
                    if (!ReceivedObject.Files.Any())
                    {
                        Console.WriteLine("\nNo files are avaialable for download at this point.");
                        taskObject.DoneFlag = true;
                        break;
                    }

                    // If there is files avaiable for download
                    Console.WriteLine("\nThere are {0} files available for download. \nThese are the downloadable files:\n", ReceivedObject.Files.Count);
                    for (int i = 0; i < ReceivedObject.Files.Count; i++)
                    {
                        var file   = ReceivedObject.Files[i];
                        var length = ReceivedObject.FilesLength[i];
                        Console.WriteLine("{0}) {1}     Size: {2} bytes", i + 1, file, length);
                        taskObject.DownloadableFiles.Add(file);
                        taskObject.DownloadableFilesLength.Add(length);
                    }
                    taskObject.DoneFlag = true;

                    break;

                case (int)ServerClientMsg.Commands.FileLocRly:

                    taskObject.FileToDownloadLength   = ReceivedObject.SizeOfFile;
                    taskObject.AddressAtFile2Download = ReceivedObject.IPAddresses;
                    taskObject.PortAtFile2Download    = ReceivedObject.Ports;

                    taskObject.DoneFlag = true;

                    break;

                case (int)ServerClientMsg.Commands.DataRly:
                    taskObject.ResultFileSegment   = ReceivedObject.ResultingDataSegment;
                    taskObject.ResultFileHash      = ReceivedObject.HashOfFile;
                    taskObject.ResultFileSegmentNo = ReceivedObject.SegmentOfFile;

                    taskObject.DoneFlag = true;
                    break;

                // if it is leave replay then we don't need to do anything
                case (int)ServerClientMsg.Commands.LeaveRly:
                    Console.WriteLine("\nThe program is ready for shutdown. Press any key to close the program");
                    taskObject.DoneFlag = true;
                    break;
                }
            }
        }
Exemplo n.º 6
0
        private async Task OnTransferAsync(TcpClient tcpClient, StateObject tcpState)
        {
            await Task.Yield();

            using (var networkStream = tcpClient.GetStream())
            {
                var buffer = new byte[8192];


                var byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);
                if (byteCount > 0)
                {
                    ServerSb.Append(Encoding.UTF8.GetString(buffer, 0, byteCount));
                    var StringMsg = ServerSb.ToString();
                    if (StringMsg.IndexOf("</TcpMsg>") > -1)
                    {
                        var xmlSerializer = new XmlSerializer(typeof(ServerClientMsg));
                        var ReceivedMsgObject = new ServerClientMsg();
                        using (var textReader = new StringReader(StringMsg))
                        {
                            ReceivedMsgObject = (ServerClientMsg)xmlSerializer.Deserialize(textReader);
                        }

                        // Clear string builder since we are done with it 
                        ServerSb.Clear();

                        var MsgObjectToReturn = new ServerClientMsg();

                        // If this thread if for the server
                        if (tcpState.ClientType == false)
                        {
                            MsgObjectToReturn = ServerCreateRly(ReceivedMsgObject);
                        }
                        // If this thread if for the client 
                        else
                        {
                            Console.WriteLine("client Server received {0} command", ReceivedMsgObject.Command);
                            switch (ReceivedMsgObject.Command)
                            {
                                case (int)ServerClientMsg.Commands.DataRq:

                                    string file = string.Empty;
                                    string hash = string.Empty;

                                    Console.WriteLine("ClientServer received the data request");

                                    foreach (var pair in tcpState.FileDict)
                                    {
                                        if (pair.Key == ReceivedMsgObject.NameOfFile)
                                        {
                                            ObjectForFiledict resultObj = pair.Value;
                                            file = resultObj.Segments[ReceivedMsgObject.SegmentOfFile];
                                            hash = resultObj.Hash;

                                            if (!file.Any() || String.IsNullOrEmpty(hash))
                                            {
                                                Console.WriteLine("string or hash is empty");
                                            }
                                            
                                        }
                                    }
                                    Console.WriteLine("ClientServer is sending string: {0} \nWith a hash of: {1}", file, hash);
                                    MsgObjectToReturn.DataRly(hash, ReceivedMsgObject.SegmentOfFile, file);

                                    break;
                                default:
                                    Console.WriteLine("Invalid command to the client server");
                                    break;
                            }
                        }


                        StringBuilder SerializedSb = new StringBuilder();

                        using (var stringWriter = new StringWriter())
                        {
                            xmlSerializer.Serialize(stringWriter, MsgObjectToReturn);
                            SerializedSb.Append(stringWriter.ToString());
                        }

                        var serializedString = SerializedSb.ToString();
                        var MsgToSend = Encoding.UTF8.GetBytes(serializedString);
                        await networkStream.WriteAsync(MsgToSend, 0, MsgToSend.Length);

                            //Console.WriteLine("[Server] Response has been given");
                        }
                    }
                }
            }
Exemplo n.º 7
0
        private async Task OnTransferAsync(TcpClient tcpClient, StateObject tcpState)
        {
            await Task.Yield();

            using (var networkStream = tcpClient.GetStream())
            {
                var buffer = new byte[8192];


                var byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);

                if (byteCount > 0)
                {
                    ServerSb.Append(Encoding.UTF8.GetString(buffer, 0, byteCount));
                    var StringMsg = ServerSb.ToString();
                    if (StringMsg.IndexOf("</TcpMsg>") > -1)
                    {
                        var xmlSerializer     = new XmlSerializer(typeof(ServerClientMsg));
                        var ReceivedMsgObject = new ServerClientMsg();
                        using (var textReader = new StringReader(StringMsg))
                        {
                            ReceivedMsgObject = (ServerClientMsg)xmlSerializer.Deserialize(textReader);
                        }

                        // Clear string builder since we are done with it
                        ServerSb.Clear();

                        var MsgObjectToReturn = new ServerClientMsg();

                        // If this thread if for the server
                        if (tcpState.ClientType == false)
                        {
                            MsgObjectToReturn = ServerCreateRly(ReceivedMsgObject);
                        }
                        // If this thread if for the client
                        else
                        {
                            Console.WriteLine("client Server received {0} command", ReceivedMsgObject.Command);
                            switch (ReceivedMsgObject.Command)
                            {
                            case (int)ServerClientMsg.Commands.DataRq:

                                string file = string.Empty;
                                string hash = string.Empty;

                                Console.WriteLine("ClientServer received the data request");

                                foreach (var pair in tcpState.FileDict)
                                {
                                    if (pair.Key == ReceivedMsgObject.NameOfFile)
                                    {
                                        ObjectForFiledict resultObj = pair.Value;
                                        file = resultObj.Segments[ReceivedMsgObject.SegmentOfFile];
                                        hash = resultObj.Hash;

                                        if (!file.Any() || String.IsNullOrEmpty(hash))
                                        {
                                            Console.WriteLine("string or hash is empty");
                                        }
                                    }
                                }
                                Console.WriteLine("ClientServer is sending string: {0} \nWith a hash of: {1}", file, hash);
                                MsgObjectToReturn.DataRly(hash, ReceivedMsgObject.SegmentOfFile, file);

                                break;

                            default:
                                Console.WriteLine("Invalid command to the client server");
                                break;
                            }
                        }


                        StringBuilder SerializedSb = new StringBuilder();

                        using (var stringWriter = new StringWriter())
                        {
                            xmlSerializer.Serialize(stringWriter, MsgObjectToReturn);
                            SerializedSb.Append(stringWriter.ToString());
                        }

                        var serializedString = SerializedSb.ToString();
                        var MsgToSend        = Encoding.UTF8.GetBytes(serializedString);
                        await networkStream.WriteAsync(MsgToSend, 0, MsgToSend.Length);

                        //Console.WriteLine("[Server] Response has been given");
                    }
                }
            }
        }
Exemplo n.º 8
0
        public async Task ClientSend(NetworkStream networkStream ,ServerClientMsg objectToClient)
        {
            var xmlSerializer = new XmlSerializer(objectToClient.GetType());

            StringBuilder SerializedSb = new StringBuilder();

            using (var stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, objectToClient);
                SerializedSb.Append(stringWriter.ToString());
            }

            var serializedString = SerializedSb.ToString();
            var MsgToSend = Encoding.UTF8.GetBytes(serializedString);
            await networkStream.WriteAsync(MsgToSend, 0, MsgToSend.Length);
        }
Exemplo n.º 9
0
        public async Task<ServerClientMsg> ClientReceive(NetworkStream networkStream)
        {
            var ReadBytes = new byte[8192];
            ServerClientMsg ReceivedObject = new ServerClientMsg();

            int BytesRead = await networkStream.ReadAsync(ReadBytes, 0, ReadBytes.Length);
            if (BytesRead > 0)
            {
                ClientSb.Append(Encoding.UTF8.GetString(ReadBytes, 0, BytesRead));
                var ReceivedMsg = ClientSb.ToString();
                if (ReceivedMsg.IndexOf("</TcpMsg>") > -1)
                {
                    XmlSerializer xmlS = new XmlSerializer(typeof(ServerClientMsg));
                    using (var stringReader = new StringReader(ReceivedMsg))
                    {
                        ReceivedObject = (ServerClientMsg)xmlS.Deserialize(stringReader);
                    }
                    ClientSb.Clear();
                }
            }
            return ReceivedObject;
            
        }
Exemplo n.º 10
0
        private async Task ClientOnTransferAsync(TcpClient tcpclient, ClientPassableObject taskObject)
        {
            await Task.Yield();

            using (var networkStream = tcpclient.GetStream())
            {
                //var SendBytes = Encoding.UTF8.GetBytes("Hello this is the Client");
                //await networkStream.WriteAsync(SendBytes, 0, SendBytes.Length);
                //var ReceivedBytes = new byte[1024];
                //await networkStream.ReadAsync(ReceivedBytes, 0, ReceivedBytes.Length);
                //Console.WriteLine(Encoding.UTF8.GetString(ReceivedBytes));

                var objectToClient = new ServerClientMsg();
                switch (taskObject.command)
                {
                    case (int)ClientPassableObject.enCommands.RegFiles:
                        objectToClient.RegisterRq(taskObject.address, taskObject.port, taskObject.FilesToReg, taskObject.FilesLength);
                        break;

                    case (int)ClientPassableObject.enCommands.PrintDownloadable:
                        objectToClient.FileListRq();
                        break;

                    case (int)ClientPassableObject.enCommands.Leave:
                        objectToClient.LeaveRq(taskObject.address, taskObject.port);
                        break;
                    case (int)ClientPassableObject.enCommands.FileLocation:
                        objectToClient.FileLocRq(taskObject.FileToDownload);
                        break;
                    case (int)ClientPassableObject.enCommands.GetFile:
                        objectToClient.DataRq(taskObject.FileToDownload, taskObject.FileSegmentToDownload);
                        break;
                }
                await ClientSend(networkStream, objectToClient);

                // Start receiving reply from the server
                ServerClientMsg ReceivedObject = await ClientReceive(networkStream);
                switch (ReceivedObject.Command)
                {
                    // If it is a Register file reply then tell the user which file was successful. 
                    case (int)ServerClientMsg.Commands.RegisterRly:
                        Console.WriteLine("");
                        for(int i = 0; i < taskObject.FilesLength.Count; i++)
                        {
                            if (ReceivedObject.SuccessCount[i] == true)
                            {
                                Console.WriteLine("You have successfully registered file: {0}", Path.GetFileName(taskObject.FilesToReg[i]));
                            }
                            else
                            {
                                Console.WriteLine("You were not able to registered file: {0}", Path.GetFileName(taskObject.FilesToReg[i]));
                            }
                        }
                        taskObject.FilesRegSuccessCount = ReceivedObject.SuccessCount;

                        taskObject.DoneFlag = true;

                        break;

                    // if it is a file list request then we need to print it all on the screen
                    case (int)ServerClientMsg.Commands.FileListRly:

                        // if the server did not return anything
                        if (!ReceivedObject.Files.Any())
                        {
                            Console.WriteLine("\nNo files are avaialable for download at this point.");
                            taskObject.DoneFlag = true;
                            break;
                        }

                        // If there is files avaiable for download
                        Console.WriteLine("\nThere are {0} files available for download. \nThese are the downloadable files:\n", ReceivedObject.Files.Count);
                        for (int i = 0; i < ReceivedObject.Files.Count; i++)
                        {
                            var file = ReceivedObject.Files[i];
                            var length = ReceivedObject.FilesLength[i];
                            Console.WriteLine("{0}) {1}", i + 1, file);
                            taskObject.DownloadableFiles.Add(file);
                            taskObject.DownloadableFilesLength.Add(length);
                        }
                        taskObject.DoneFlag = true;

                        break;

                    case (int)ServerClientMsg.Commands.FileLocRly:

                        taskObject.FileToDownloadLength = ReceivedObject.SizeOfFile;
                        taskObject.AddressAtFile2Download = ReceivedObject.IPAddresses;
                        taskObject.PortAtFile2Download = ReceivedObject.Ports;

                        taskObject.DoneFlag = true;

                        break;

                    case (int)ServerClientMsg.Commands.DataRly:
                        taskObject.ResultFileSegment = ReceivedObject.ResultingDataSegment;
                        taskObject.ResultFileHash = ReceivedObject.HashOfFile;
                        taskObject.ResultFileSegmentNo = ReceivedObject.SegmentOfFile;

                        taskObject.DoneFlag = true;
                        break;

                    // if it is leave replay then we don't need to do anything
                    case (int)ServerClientMsg.Commands.LeaveRly:
                        Console.WriteLine("\nThe program is ready for shutdown. Press any key to close the program");
                        taskObject.DoneFlag = true;
                        break;


                }
                
            }
        }
Exemplo n.º 11
0
        public ServerClientMsg ServerCreateRly(ServerClientMsg ReceivedMsgObject)
        {
            var MsgObjectToReturn = new ServerClientMsg();
            switch (ReceivedMsgObject.Command)
            {


                // If we received a Register Files message from the client
                case (int)ServerClientMsg.Commands.RegisterRq:
                    List<bool> SuccessList = new List<bool>();
                    // Looping through all the messages and add it to the dictionary if possible
                    for (int i = 0; i < ReceivedMsgObject.Files.Count; i++)
                    {
                        if (!ServerDict.ContainsKey(ReceivedMsgObject.Files[i]))
                        {
                            ServerDataObject Sdo = new ServerDataObject();
                            // Store each success and failure in a list for a message back to the client
                            SuccessList.Add(Sdo.AddEndPoint(ReceivedMsgObject.ClientIP, ReceivedMsgObject.ClientPort));
                            Sdo.Length = ReceivedMsgObject.FilesLength[i];
                            ServerDict.Add(ReceivedMsgObject.Files[i], Sdo);
                        }
                        else
                        {
                            bool successflag = false;
                            foreach (var pair in ServerDict)
                            {
                                if (pair.Key == ReceivedMsgObject.Files[i])
                                {
                                    ServerDataObject ServObj = pair.Value;
                                    for (int k =0; k < ServObj.Addresses.Count; k++)
                                    {
                                        if (ServObj.Ports[k] == ReceivedMsgObject.ClientPort)
                                        {
                                            if (ServObj.Addresses[k] == ReceivedMsgObject.ClientIP)
                                                successflag = false;
                                        }
                                        else
                                        {
                                            ServObj.AddEndPoint(ReceivedMsgObject.ClientIP, ReceivedMsgObject.ClientPort);
                                            successflag = true;
                                        }
                                    }
                                }
                            }

                            SuccessList.Add(successflag);

                        }
                    }
                    // Compile the return message for the client
                    MsgObjectToReturn.RegisterRly(SuccessList);

                    break;

                // If we received a file list request from the client
                case (int)ServerClientMsg.Commands.FileListRq:

                    // For a fileName list and a file size list
                    List<string> fileName = new List<string>();
                    List<int> fileSize = new List<int>();

                    foreach (var pair in ServerDict)
                    {
                        fileName.Add(pair.Key);
                        ServerDataObject obj = pair.Value;
                        fileSize.Add(obj.Length);
                    }
                    MsgObjectToReturn.FileListRly(fileName, fileSize);
                    break;

                // If we received a file location request from the client
                case (int)ServerClientMsg.Commands.FileLocRq:

                    // For a fileName list and a file size list
                    List<string> addresses = new List<string>();
                    List<int> ports = new List<int>();
                    int length = 0;

                    foreach (var pair in ServerDict)
                    {
                        if (pair.Key == ReceivedMsgObject.NameOfFile)
                        {
                            ServerDataObject SObj = pair.Value;
                            addresses = SObj.Addresses;
                            ports = SObj.Ports;
                            length = SObj.Length;

                        }
                    }

                    MsgObjectToReturn.FileLocRly(length, addresses, ports);


                    break;

                // On leave request, the server need to remove all files that has the client's ip address. 
                // if the client is the last address that is associated with that file, then the server needs to remove the file
                case (int)ServerClientMsg.Commands.LeaveRq:

                    List<string> FilestoRemove = new List<string>();

                    foreach (var pair in ServerDict)
                    {
                        List<int> indexToRemove = new List<int>();

                        ServerDataObject objOfFile = pair.Value;
                        for (int i = 0; i < objOfFile.Addresses.Count; i++)
                        {
                            if (objOfFile.Addresses[i] == ReceivedMsgObject.ClientIP)
                            {
                                if (objOfFile.Ports[i] == ReceivedMsgObject.ClientPort)
                                    indexToRemove.Add(i);
                            }
                        }
                        // This allows the removal process to be skipped if the client doesn't have this file 
                        if (indexToRemove.Any())
                        {
                            foreach (var index in indexToRemove)
                            {
                                objOfFile.Addresses.RemoveAt(index);
                                objOfFile.Ports.RemoveAt(index);

                            }
                            if (!objOfFile.Addresses.Any())
                            {
                                FilestoRemove.Add(pair.Key);
                            }
                        }

                    }

                    // Now the server has to remove all the files that doesn't have any clients on it
                    if (FilestoRemove.Any())
                    {
                        foreach (var key in FilestoRemove)
                        {
                            ServerDict.Remove(key);
                        }
                    }


                    MsgObjectToReturn.LeaveRly();
                    break;
                case (int)ServerClientMsg.Commands.DataRly:
                    Console.WriteLine("Requesting Data from server instead of client");
                    break;
                default:
                    break;
            }
            return MsgObjectToReturn;
        }
Exemplo n.º 12
0
        private async Task OnTransferAsync(TcpClient tcpClient, StateObject tcpState)
        {
            await Task.Yield();

            using (var networkStream = tcpClient.GetStream())
            {
                var buffer = new byte[8192];

                // Receiving and deserialized the serializable object
                var byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);
                if (byteCount > 0)
                {
                    ServerSb.Append(Encoding.UTF8.GetString(buffer, 0, byteCount));
                    var StringMsg = ServerSb.ToString();
                    if (StringMsg.IndexOf("</TcpMsg>") > -1)
                    {
                        var xmlSerializer = new XmlSerializer(typeof(ServerClientMsg));
                        var ReceivedMsgObject = new ServerClientMsg();
                        using (var textReader = new StringReader(StringMsg))
                        {
                            ReceivedMsgObject = (ServerClientMsg)xmlSerializer.Deserialize(textReader);
                        }

                        // Clear string builder since we are done with it 
                        ServerSb.Clear();

                        var MsgObjectToReturn = new ServerClientMsg();

                        // If this thread is for the server
                        if (tcpState.ClientType == false)
                        {
                            MsgObjectToReturn = ServerCreateRly(ReceivedMsgObject);
                        }
                        // If this thread if for the client 
                        else
                        {
                            
                            // Now that we have the serializable object, we need to switch through all the commands
                            switch (ReceivedMsgObject.Command)
                            {
                                // Data request command
                                case (int)ServerClientMsg.Commands.DataRq:

                                    byte[] file;
                                    string hash = string.Empty;
                                    //Console.WriteLine("Client Server: received data request for file: {0} segment: {1}", ReceivedMsgObject.NameOfFile,ReceivedMsgObject.SegmentOfFile);

                                    string filepath = tcpState.TempFolderPath + @"/" + Path.GetFileNameWithoutExtension(ReceivedMsgObject.NameOfFile);
                                    filepath += "_temp" + ReceivedMsgObject.SegmentOfFile + Path.GetExtension(ReceivedMsgObject.NameOfFile);
                                    //Console.WriteLine("Client Server: Retreiving file: {0}", filepath);

                                    // See if the client's server actually has the file or not
                                    if (File.Exists(filepath))
                                    {
                                        file = File.ReadAllBytes(filepath);
                                    }
                                    else
                                    {
                                        //Console.WriteLine("Client Server could not find the file {0}", filepath);
                                        file = new byte[2];
                                    }

                                    // Retrieveing the hash to send back with the data segment
                                    foreach (var pair in tcpState.FileDict)
                                    {
                                        if(pair.Key == ReceivedMsgObject.NameOfFile)
                                        {
                                            ObjectForFiledict obj = pair.Value;
                                            hash = obj.Hash;
                                            //Console.WriteLine("Client Server: Hash = {0}", hash);
                                            break;
                                        }
                                    }
                                    
                                    MsgObjectToReturn.DataRly(hash, ReceivedMsgObject.SegmentOfFile, file);

                                    break;
                                default:
                                    Console.WriteLine("Invalid command to the client server");
                                    break;
                            }
                        }

                        // At this point, the serializable object should be popululated with the proper command and info
                        StringBuilder SerializedSb = new StringBuilder();

                        using (var stringWriter = new StringWriter())
                        {
                            xmlSerializer.Serialize(stringWriter, MsgObjectToReturn);
                            SerializedSb.Append(stringWriter.ToString());
                        }

                        var serializedString = SerializedSb.ToString();
                        var MsgToSend = Encoding.UTF8.GetBytes(serializedString);

                        // Sending the serializable response back
                        await networkStream.WriteAsync(MsgToSend, 0, MsgToSend.Length);

                            //Console.WriteLine("[Server] Response has been given");
                        }
                    }
                }
            }