예제 #1
0
        private void SendFile(string absolutePath, string fileName, Client client)
        {
            FileStream fileStream = new FileStream(absolutePath, FileMode.Open, FileAccess.Read);

            byte[] buffer = new byte[maxSegmentSize];

            long length        = fileStream.Length;
            long segmentCount  = 1;
            long totalSegments = (long)Math.Ceiling((double)length / buffer.Length);

            long pos = 0;

            Console.WriteLine("File length: " + length);
            while (pos < length)
            {
                int bytesRead = fileStream.Read(buffer, 0, buffer.Length);

                byte[] data = new byte[bytesRead];
                Array.Copy(buffer, 0, data, 0, bytesRead);

                FyzrPacket packet = FileProtocol.CreateFilePacket(data, fileName, MessageProtocol.MessageType.PRIVATE, null);
                packet.headers.Add("Total-Length", "" + length);
                packet.headers.Add("Total-Segments", "" + totalSegments);
                packet.headers.Add("Segment", "" + segmentCount);
                packet.headers.Add("Position", "" + pos);

                client.SendRandom(FyzrParser.ToData(packet));
                pos += buffer.Length;
                Console.WriteLine("Count: " + segmentCount++);
                Console.WriteLine("Bytes read: " + bytesRead);
            }
        }
예제 #2
0
        internal void SendMessage(ChatWindow chatWindow, TextMessage msg)
        {
            var client = chats.FirstOrDefault(x => x.Value == chatWindow).Key;
            var packet = TextProtocol.CreateTextPacket(msg.Text, MessageProtocol.MessageType.PRIVATE, null);

            packet.headers.Add("Username", ownUsername);
            client.SendOrdered(FyzrParser.ToData(packet));
        }
예제 #3
0
        public void SendDisconnect()
        {
            FyzrPacket packet = new FyzrPacket();

            packet.method = FyzrPacket.Method.COMMAND;
            packet.headers.Add("Command-Type", "disconnect");
            packet.headers.Add("Username", ownUsername);

            coordinator.SendOrdered(FyzrParser.ToData(packet));
        }
예제 #4
0
        public void RequestUsersList()
        {
            FyzrPacket packet = new FyzrPacket();

            packet.method = FyzrPacket.Method.COMMAND;
            packet.headers.Add("Command-Type", "requestUsersUpdate");
            packet.headers.Add("Listener-Port", "" + ownServer.listener.LocalEndpoint.ToString().Split(':')[1]);

            coordinator.SendOrdered(FyzrParser.ToData(packet));
        }
예제 #5
0
        private void Coordinator_PacketReceived(object sender, Core.Events.PacketFullyReceivedEventArgs e)
        {
            FyzrPacket packet = FyzrParser.FromData(e.Packet.data.ToArray());

            if (packet.method == FyzrPacket.Method.COMMAND)
            {
                string cmdType = packet.headers["Command-Type"];
                if (cmdType.Equals("usersList"))
                {
                    users.Clear();
                    Encoding enc = Encoding.GetEncoding(packet.headers["Content-Encoding"]);
                    if (packet.body != null)
                    {
                        string body = enc.GetString(packet.body);



                        string[] lines = body.Split('\n');
                        foreach (string line in lines)
                        {
                            string[] splitted = line.Trim().Split('#');
                            string[] endPoint = splitted[1].Split(':');
                            users.Add(new User()
                            {
                                Username = splitted[0], Endpoint = new IPEndPoint(IPAddress.Parse(endPoint[0]), Convert.ToInt32(endPoint[1]))
                            });
                        }

                        var handler = UsersListReceived;
                        if (handler != null)
                        {
                            handler(this, new UsersListReceivedEventArgs());
                        }
                    }
                    else
                    {
                        var handler = UsersListReceived;
                        if (handler != null)
                        {
                            handler(this, new UsersListReceivedEventArgs());
                        }
                    }

                    if (requestThread == null)
                    {
                        requestThread = new Thread(RunRequestThread);
                        requestThread.Start();
                    }
                }
            }
        }
예제 #6
0
        private void btnServerSend_Click(object sender, RoutedEventArgs e)
        {
            if (txtServerMessage.Text.Trim().Length == 0)
            {
                MessageBox.Show("Enter some text first");
                return;
            }
            string message = txtServerMessage.Text;


            Client client = fromClients[0];

            client.SendOrdered(
                FyzrParser.ToData(
                    TextProtocol.CreateTextPacket(message, MessageProtocol.MessageType.PRIVATE, null)
                    ));
            Dispatcher.Invoke(() => { listServerMessages.Items.Add("Alice: " + message); });
        }
예제 #7
0
        public bool RegisterNickname(string nickname, string coordinatorIp, int coordinatorPort)
        {
            ownUsername         = nickname;
            coordinatorEndpoint = new IPEndPoint(IPAddress.Parse(coordinatorIp), coordinatorPort);
            coordinator.StartConnect(coordinatorEndpoint);
            Thread.Sleep(10);
            coordinator.PacketReceived += Coordinator_PacketReceived;
            FyzrPacket packet = new FyzrPacket();

            packet.method = FyzrPacket.Method.COMMAND;
            packet.headers.Add("Command-Type", "requestUsers");
            packet.headers.Add("Username", nickname);
            packet.headers.Add("Listener-Port", "" + ownServer.listener.LocalEndpoint.ToString().Split(':')[1]);

            coordinator.SendOrdered(FyzrParser.ToData(packet));


            return(true);
        }
예제 #8
0
        internal void SendMediaFile(ChatWindow chatWindow, string absolutePath, string fileName, MediaMessage msg)
        {
            var        client     = chats.FirstOrDefault(x => x.Value == chatWindow).Key;
            FileStream fileStream = new FileStream(absolutePath, FileMode.Open, FileAccess.Read);

            byte[] buffer = new byte[maxSegmentSize];

            long length        = fileStream.Length;
            long segmentCount  = 1;
            long sizeCount     = 0;
            long totalSegments = (long)Math.Ceiling((double)length / buffer.Length);

            long pos = 0;

            Console.WriteLine("File length: " + length);
            while (pos < length)
            {
                int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                sizeCount += bytesRead;
                byte[] data = new byte[bytesRead];
                Array.Copy(buffer, 0, data, 0, bytesRead);

                FyzrPacket packet = FileProtocol.CreateFilePacket(data, fileName, MessageProtocol.MessageType.PRIVATE, null);
                packet.headers.Add("Total-Length", "" + length);
                packet.headers.Add("Total-Segments", "" + totalSegments);
                packet.headers.Add("Segment", "" + segmentCount);
                packet.headers.Add("Position", "" + pos);
                packet.headers.Add("File-Type", "Media");
                packet.headers.Add("Username", ownUsername);

                client.SendRandom(FyzrParser.ToData(packet));
                msg.Loading  = ((double)segmentCount * 100.0 / totalSegments);
                msg.Progress = SizeSuffix(sizeCount) + "/" + SizeSuffix(length);
                pos         += buffer.Length;
                Console.WriteLine("Count: " + segmentCount++);
                Console.WriteLine("Bytes read: " + bytesRead);
                Thread.Sleep(2);
            }
        }
예제 #9
0
        private void Client_PacketReceived(object sender, DS_Chat_CS1.Core.Events.PacketFullyReceivedEventArgs e)
        {
            //Console.WriteLine("Received something");
            var        client = sender as Client;
            FyzrPacket packet = FyzrParser.FromData(e.Packet.data.ToArray());

            if (packet.method == FyzrPacket.Method.COMMAND)
            {
                string cmdType = packet.headers["Command-Type"];
                if (cmdType.Equals("requestUsers"))
                {
                    if (!packet.headers.ContainsKey("Username"))
                    {
                        return;
                    }
                    string username = packet.headers["Username"].Trim();
                    if (username.Length == 0)
                    {
                        return;
                    }
                    int port = Convert.ToInt32(packet.headers["Listener-Port"]);

                    /*
                     * Username#Endpoint#Room
                     *
                     */
                    string response = "";
                    foreach (var user in users)
                    {
                        response += user.ToString() + '\n';
                    }
                    response = response.Trim();

                    IPEndPoint endPoint = new IPEndPoint(client.GetRemoteEndPoint().Address, port);
                    var        u        = new UserObject()
                    {
                        Username = username, Endpoint = endPoint, Room = null, client = client
                    };
                    users.Add(u);
                    u.lastReceived = DateTime.Now;

                    FyzrPacket responsePacket = new FyzrPacket();
                    responsePacket.method = FyzrPacket.Method.COMMAND;
                    responsePacket.headers.Add("Content-Encoding", Encoding.Default.WebName);
                    responsePacket.body = Encoding.Default.GetBytes(response);
                    responsePacket.headers.Add("Content-Length", "" + responsePacket.body.Length);
                    responsePacket.headers.Add("Command-Type", "usersList");

                    client.SendOrdered(FyzrParser.ToData(responsePacket));
                }
                else if (cmdType.Equals("requestUsersUpdate"))
                {
                    int        port     = Convert.ToInt32(packet.headers["Listener-Port"]);
                    IPEndPoint endPoint = new IPEndPoint(client.GetRemoteEndPoint().Address, port);
                    var        u        = users.Find(x => x.Endpoint.Equals(endPoint));
                    u.lastReceived = DateTime.Now;

                    string response = "";
                    foreach (var user in users)
                    {
                        if (user != u)
                        {
                            response += user.ToString() + '\n';
                        }
                    }
                    response = response.Trim();

                    FyzrPacket responsePacket = new FyzrPacket();
                    responsePacket.method = FyzrPacket.Method.COMMAND;
                    responsePacket.headers.Add("Content-Encoding", Encoding.Default.WebName);
                    responsePacket.body = Encoding.Default.GetBytes(response);
                    responsePacket.headers.Add("Content-Length", "" + responsePacket.body.Length);
                    responsePacket.headers.Add("Command-Type", "usersList");

                    client.SendOrdered(FyzrParser.ToData(responsePacket));
                }
                else if (cmdType.Equals("disconnect"))
                {
                    Console.WriteLine("Disconnect received");
                    client.Disconnect();
                }
            }
        }
예제 #10
0
        private void Client_PacketReceived(object sender, Core.Events.PacketFullyReceivedEventArgs e)
        {
            FyzrPacket packet   = FyzrParser.FromData(e.Packet.data.ToArray());
            Client     client   = sender as Client;
            string     username = packet.headers["Username"];

            if (!chats.ContainsKey(client))
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    ChatWindow chatWindow = new ChatWindow();
                    chatWindow.SetTitle(username);
                    chatWindow.ShowWindow();
                    chats.Add(client, chatWindow);
                });
            }
            if (packet.method == FyzrPacket.Method.TEXT)
            {
                Encoding enc = Encoding.GetEncoding(packet.headers["Content-Encoding"]);

                string      message = enc.GetString(packet.body);
                TextMessage msg     = new TextMessage()
                {
                    Side = MessageSide.You,
                    Text = message
                };
                chats[client].AddTextMessage(msg);
            }
            else if (packet.method == FyzrPacket.Method.FILE)
            {
                lock (lockk)
                {
                    string fileName = packet.headers["Filename"];

                    long segmentLength = Convert.ToInt64(packet.headers["Content-Length"]);
                    long segmentCount  = Convert.ToInt64(packet.headers["Segment"]);
                    long totalSegments = Convert.ToInt64(packet.headers["Total-Segments"]);
                    long totalLength   = Convert.ToInt64(packet.headers["Total-Length"]);

                    long pos = Convert.ToInt64(packet.headers["Position"]);


                    string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDoc‌​uments) + @"\TestReceived";
                    System.IO.Directory.CreateDirectory(path);
                    path += @"\" + fileName;

                    string fileType = packet.headers["File-Type"];
                    if (fileType.Equals("Image"))
                    {
                        if (!imageFilesMap.ContainsKey(client))
                        {
                            imageFilesMap.Add(client, new List <ImageFile>());
                        }

                        ImageFile imageFile = imageFilesMap[client].FirstOrDefault(x => x.fileName.Equals(fileName));
                        if (imageFile == null)
                        {
                            imageFile = new ImageFile()
                            {
                                fileName      = fileName,
                                segmentsCount = 0,
                                sizeCount     = 0,
                                stream        = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None),
                                imageMessage  = chats[client].CreateImageMessage(fileName)
                            };
                            imageFile.stream.SetLength(totalLength);
                            imageFilesMap[client].Add(imageFile);
                        }

                        imageFile.segmentsCount++;
                        imageFile.sizeCount += segmentLength;

                        imageFile.stream.Seek(pos, SeekOrigin.Begin);

                        imageFile.stream.Write(packet.body, 0, packet.body.Length);

                        if (imageFile.segmentsCount == totalSegments)
                        {
                            imageFile.stream.Flush();
                            imageFile.stream.Close();
                            imageFile.stream = null;
                            imageFile.imageMessage.ImageUrl = path;
                            Console.WriteLine("Done file");
                            imageFilesMap[client].Remove(imageFile);
                        }

                        imageFile.imageMessage.Loading  = ((double)imageFile.segmentsCount * 100.0 / totalSegments);
                        imageFile.imageMessage.Progress = SizeSuffix(imageFile.sizeCount) + "/" + SizeSuffix(totalLength);
                    }

                    else if (fileType.Equals("Media"))
                    {
                        if (!mediaFilesMap.ContainsKey(client))
                        {
                            mediaFilesMap.Add(client, new List <MediaFile>());
                        }

                        MediaFile mediaFile = mediaFilesMap[client].FirstOrDefault(x => x.fileName.Equals(fileName));
                        if (mediaFile == null)
                        {
                            try
                            {
                                mediaFile = new MediaFile()
                                {
                                    fileName      = fileName,
                                    segmentsCount = 0,
                                    sizeCount     = 0,
                                    stream        = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None),
                                    mediaMessage  = chats[client].CreateMediaMessage(fileName)
                                };
                                mediaFile.stream.SetLength(Convert.ToInt64(packet.headers["Total-Length"]));
                                mediaFilesMap[client].Add(mediaFile);
                            } catch (Exception ex)
                            {
                                Console.WriteLine("EXCEPTION: " + ex.ToString());
                                Console.WriteLine("media map size: " + mediaFilesMap[client].Count);
                            }
                        }

                        mediaFile.segmentsCount++;
                        mediaFile.sizeCount += segmentLength;

                        mediaFile.stream.Seek(pos, SeekOrigin.Begin);

                        mediaFile.stream.Write(packet.body, 0, packet.body.Length);

                        if (mediaFile.segmentsCount == totalSegments)
                        {
                            mediaFile.stream.Flush();
                            mediaFile.stream.Close();
                            mediaFile.stream = null;
                            mediaFile.mediaMessage.MediaUrl = path;
                            Console.WriteLine("Done file");
                            mediaFilesMap[client].Remove(mediaFile);
                        }

                        mediaFile.mediaMessage.Loading  = ((double)mediaFile.segmentsCount * 100.0 / totalSegments);
                        mediaFile.mediaMessage.Progress = SizeSuffix(mediaFile.sizeCount) + "/" + SizeSuffix(totalLength);
                    }
                }
            }
        }
예제 #11
0
        private void OnPacketReceived(object sender, PacketFullyReceivedEventArgs e)
        {
            Console.WriteLine("Received Packet in MainWindow");
            List <byte> data   = e.Packet.data;
            FyzrPacket  packet = FyzrParser.FromData(data.ToArray());


            switch (packet.method)
            {
            case FyzrPacket.Method.TEXT:
                Encoding enc = Encoding.GetEncoding(packet.headers["Content-Encoding"]);

                string message = enc.GetString(packet.body);
                if (toClients.Count != 0 && sender == toClients[0])     //From Alice
                {
                    Dispatcher.Invoke(() => { listClientMessages.Items.Add("Alice: " + message); });
                }
                else
                {
                    Dispatcher.Invoke(() => { listServerMessages.Items.Add("Bob: " + message); });
                }
                break;

            case FyzrPacket.Method.FILE:

                lock (filesMap)
                {
                    string     fileName = packet.headers["Filename"];
                    string     path     = @"D:\College\AAST\Sixth semester\" + fileName;
                    FileStream fs;
                    if (!filesMap.ContainsKey(fileName))
                    {
                        filesMap.Add(fileName, new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None));
                        filesMap[fileName].SetLength(Convert.ToInt32(packet.headers["Total-Length"]));

                        filesSegmentsMap.Add(fileName, 0);
                    }

                    fs = filesMap[fileName];
                    filesSegmentsMap[fileName]++;

                    int segmentLength = Convert.ToInt32(packet.headers["Content-Length"]);
                    int segmentCount  = Convert.ToInt32(packet.headers["Segment"]);
                    int totalSegments = Convert.ToInt32(packet.headers["Total-Segments"]);

                    long pos = Convert.ToInt32(packet.headers["Position"]);

                    fs.Seek(pos, SeekOrigin.Begin);

                    fs.Write(packet.body, 0, packet.body.Length);

                    if (filesSegmentsMap[fileName] == totalSegments)
                    {
                        fs.Flush();
                        fs.Close();
                        fs = null;
                        filesMap.Remove(fileName);
                        filesSegmentsMap.Remove(fileName);
                        Console.WriteLine("Done file");
                    }
                }

                Dispatcher.Invoke(() =>
                {
                    int count = Convert.ToInt32(lblSecondSegments.Content);
                    count++;
                    lblSecondSegments.Content = count;
                });


                //Dispatcher.Invoke(() =>
                //{
                //    int count = Convert.ToInt32(lblServerSegments.Content);
                //    count++;
                //    lblServerSegments.Content = count;
                //});

                break;
            }
        }