예제 #1
0
        private async Task SaveBodyAsync(BodySetting bodySetting, BodyResult <int, int, BodyFailedItem> bodyResult, RetrySettings retrySettings_4FailedItems)
        {
            Console.WriteLine();
            Console.WriteLine("#################### Saving Stats ####################");
            Console.WriteLine();
            Console.WriteLine("Total counts : " + bodySetting.Items.Count);
            Console.WriteLine("Successed Count: :" + bodyResult.SuccessList.Count);
            Console.WriteLine("Failed Count: :" + bodyResult.FailedList.Count);
            Console.WriteLine();
            Console.WriteLine("######################################################");
            Console.WriteLine();
            var utcNow = DateTime.UtcNow;


            //===================================================================================================================================================================================
            // TelegramPortStat تلاش برای اضافه کردن آمار فالور کانال‌هایی که آمارگیری شدند به جدول
            try
            {
                // ذخیره سازی دسته جمعی موفق‌ها
                TelegramPortStatService.BatchAdd(bodyResult.SuccessList.Select(x => new AddPortStatViewModel
                {
                    TelegramPortId = x.Key,
                    FollowerCount  = x.Value,
                    Createdn       = utcNow
                }).ToList());

                // نوتیفای راجع به موفق‌ها به مدیران هلپریکس
                await BotService.NotifyAdmin_TgPortStatJob_SuccessItems_ThatSavedSuccessfullyAsync(_statGroupKey, bodySetting.Items.Count, bodyResult.SuccessList.Count);
            }
            catch (Exception ex)
            {
                Inf.Utility.WriteError(ex, GetType().Name, MethodBase.GetCurrentMethod().Name, "Err Code: 1001- The error occured on BulkInsert > Saving new follower counts.");
                // افزودن موفقهایی که در زمان ثبت با مشکل روبرو شدند به لیست شکست‌خورده‌ها
                bodyResult.FailedList.AddRange(bodySetting.Items.Where(x => bodyResult.SuccessList.Select(y => y.Key).Contains(x.TelegramPortId)).Select(x => new BodyFailedItem(x)).ToList());
                // نوتیفای به مدیران هلپریکس درباره خطای ایجاد شده
                await BotService.NotifyAdmin_TgPortStatJob_SuccessItems_ThatFailedToSaveAsync(_statGroupKey, bodySetting.Items.Count, bodyResult.SuccessList.Count);
            }

            //===================================================================================================================================================================================
            // TelegramPort تلاش برای آپدیت کردن تعدادفالور کانالهایی که آمارگیری شدند در جدول
            try
            {
                var dic_TelegramPortId_ChangedFields = bodyResult.SuccessList.ToDictionary(
                    successItem => successItem.Key,
                    successItem => new Dictionary <string, string>
                {
                    {
                        "FollowerCount", successItem.Value.ToString()
                    },
                    {
                        "FollowerCountUpdateDt", $"'{utcNow:yyyy-MM-dd hh:mm:ss}'"     //    '2012-10-20 22:40:30'   مثال:
                    },
예제 #2
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("사용법 : {0} <Server IP> <File Path>", Process.GetCurrentProcess().ProcessName);
                return;
            }

            string    serverIp   = args[0];
            const int serverPort = 5425;
            string    filepath   = args[1];

            try
            {
                //클라이언트는 OS에서 할당한 IP주소와 포트에 바인딩
                IPEndPoint clientAddress = new IPEndPoint(0, 0);
                IPEndPoint serverAddress = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);

                Console.WriteLine("클라이언트 : {0}, 서버 : {1}", clientAddress.ToString(), serverAddress.ToString());

                uint msgId = 0;

                //파일 전송을 요청하는 메시지. 파일이름과 파일크기로 구성되어 있음
                Message reqMsg = new Message();
                reqMsg.Body = new BodyRequest()
                {
                    FILESIZE = new FileInfo(filepath).Length,
                    FILENAME = System.Text.Encoding.Default.GetBytes(filepath)
                };
                reqMsg.Header = new Header()
                {
                    MSGID      = msgId++,
                    MSGTYPE    = CONSTANTS.REQ_FILE_SEND,
                    BODYLEN    = (uint)reqMsg.Body.GetSize(),
                    FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                    LASTMSG    = CONSTANTS.LASTMSG,
                    SEQ        = 0
                };

                TcpClient client = new TcpClient(clientAddress);
                client.Connect(serverAddress);
                NetworkStream stream = client.GetStream();

                MessageUtil.Send(stream, reqMsg);             //클라이언트는 서버에 접속하자마자 파일 전송 요청 메시지를 보냄
                Message rspMsg = MessageUtil.Receive(stream); //서버의 응답 받기

                if (rspMsg.Header.MSGTYPE != CONSTANTS.REP_FILE_SEND)
                {
                    Console.WriteLine("정상적인 서버 응답이 아닙니다. {0}", rspMsg.Header.MSGTYPE);
                    return;
                }

                if (((BodyResponse)rspMsg.Body).RESPONSE == CONSTANTS.DENIED)
                {
                    Console.WriteLine("서버에서 파일 전송을 거부했습니다.");
                    return;
                }

                //서버에서 전송 요청을 수락했다면 파일 스트림을 열어 서버로 보낼 준비를 함ㄷ
                using (Stream fileStream = new FileStream(filepath, FileMode.Open))
                {
                    byte[] rbytes    = new byte[CHUNK_SIZE];
                    long   readValue = BitConverter.ToInt64(rbytes, 0);

                    int    totalRead  = 0;
                    ushort msgSeq     = 0;
                    byte   fragmented = (fileStream.Length < CHUNK_SIZE) ? CONSTANTS.NOT_FRAGMENTED : CONSTANTS.FRAGMENTED; //버퍼 사이즈보다 작으면 단일 파일. 아니면 분할로 전송

                    while (totalRead < fileStream.Length)
                    {
                        //Console.WriteLine("totalRead :{0}, fielStream.Length:{1}", totalRead, fileStream.Length);
                        int read = fileStream.Read(rbytes, 0, CHUNK_SIZE);
                        totalRead += read;
                        Message fileMsg = new Message();

                        byte[] sendBytes = new byte[read];
                        Array.Copy(rbytes, 0, sendBytes, 0, read);
                        fileMsg.Body   = new BodyData(sendBytes);
                        fileMsg.Header = new Header()
                        {
                            MSGID      = msgId,
                            MSGTYPE    = CONSTANTS.FILE_SEND_DATA,
                            BODYLEN    = (uint)fileMsg.Body.GetSize(),
                            FRAGMENTED = fragmented,
                            LASTMSG    = (totalRead < fileStream.Length) ? CONSTANTS.NOT_LASTMSG : CONSTANTS.LASTMSG,
                            SEQ        = msgSeq++
                        };

                        Console.Write("#");
                        MessageUtil.Send(stream, fileMsg); //모든 파일의 내용이 전송될 때까지 파일 스트림을 0x03메시지에 담아 서버로 보냄
                    }

                    Console.WriteLine();

                    //서버에서 파일을 제대로 받았는지에 대한 응답
                    Message rstMsg = MessageUtil.Receive(stream);

                    BodyResult result = ((BodyResult)rstMsg.Body);
                    Console.WriteLine("파일 전송 성공 : {0}", result.RESULT == CONSTANTS.SUCCESS);
                }
                stream.Close();
                client.Close();
            }
            catch (SocketException e)
            {
                Console.WriteLine(e);
            }

            Console.WriteLine("클라이언트를 종료합니다.");
        }
예제 #3
0
        private void Btn_sendfile_Click(object sender, EventArgs e)
        {
            try
            {
                IPEndPoint clientAddress = new IPEndPoint(0, 0);
                IPEndPoint serverAddress =
                    new IPEndPoint(IPAddress.Parse(Server_IP), serverPort);

                Console.WriteLine("클라이언트: {0}, 서버:{1}",
                                  clientAddress.ToString(), serverAddress.ToString());

                uint msgId = 0;

                FUP.Message reqMsg = new FUP.Message();
                reqMsg.Body = new BodyRequest()
                {
                    FILESIZE = new FileInfo(filepath).Length,
                    FILENAME = System.Text.Encoding.Default.GetBytes(filepath)
                };
                reqMsg.Header = new Header()
                {
                    MSGID      = msgId++,
                    MSGTYPE    = CONSTANTS.REQ_FILE_SEND,
                    BODYLEN    = (uint)reqMsg.Body.GetSize(),
                    FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                    LASTMSG    = CONSTANTS.LASTMSG,
                    SEQ        = 0
                };

                TcpClient client = new TcpClient(clientAddress);
                client.Connect(serverAddress);

                NetworkStream stream = client.GetStream();

                MessageUtil.Send(stream, reqMsg);

                FUP.Message rspMsg = MessageUtil.Receive(stream);

                if (rspMsg.Header.MSGTYPE != CONSTANTS.REP_FILE_SEND)
                {
                    LB_serverST.Text = "정상적인 서버 응답이 아닙니다.";
                    return;
                }

                if (((BodyResponse)rspMsg.Body).RESPONSE == CONSTANTS.DENIED)
                {
                    LB_serverST.Text = "서버에서 파일 전송을 거부했습니다.";
                    return;
                }
                LB_serverST.Text = "서버 접속 성공";

                using (Stream fileStream = new FileStream(filepath, FileMode.Open))
                {
                    byte[] rbytes = new byte[CHUNK_SIZE];

                    long readValue = BitConverter.ToInt64(rbytes, 0);

                    int    totalRead  = 0;
                    ushort msgSeq     = 0;
                    byte   fragmented =
                        (fileStream.Length < CHUNK_SIZE) ?
                        CONSTANTS.NOT_FRAGMENTED : CONSTANTS.FRAGMENTED;
                    while (totalRead < fileStream.Length)
                    {
                        int read = fileStream.Read(rbytes, 0, CHUNK_SIZE);
                        totalRead += read;
                        FUP.Message fileMsg = new FUP.Message();

                        byte[] sendBytes = new byte[read];
                        Array.Copy(rbytes, 0, sendBytes, 0, read);

                        fileMsg.Body   = new BodyData(sendBytes);
                        fileMsg.Header = new Header()
                        {
                            MSGID      = msgId,
                            MSGTYPE    = CONSTANTS.FILE_SEND_DATA,
                            BODYLEN    = (uint)fileMsg.Body.GetSize(),
                            FRAGMENTED = fragmented,
                            LASTMSG    = (totalRead < fileStream.Length) ?
                                         CONSTANTS.NOT_LASTMSG :
                                         CONSTANTS.LASTMSG,
                            SEQ = msgSeq++
                        };

                        progressBar1.Value = (int)(((double)totalRead / (double)fileStream.Length) * progressBar1.Maximum);

                        MessageUtil.Send(stream, fileMsg);
                    }

                    Console.WriteLine();

                    FUP.Message rstMsg = MessageUtil.Receive(stream);

                    BodyResult result = ((BodyResult)rstMsg.Body);
                    Console.WriteLine("파일 전송 성공 : {0}",
                                      result.RESULT == CONSTANTS.SUCCESS);
                }

                stream.Close();
                client.Close();
            }
            catch (SocketException ae)
            {
                Console.WriteLine(ae);
            }

            MessageBox.Show("클라이언트를 종료합니다");
        }
예제 #4
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                WriteLine($"Usage : {Process.GetCurrentProcess().ProcessName} <Server IP> <File Path>");
                return;
            }

            string    serverIp   = args[0];
            const int serverPort = 5425;
            string    filepath   = args[1];

            FileInfo fileinfo = new FileInfo(args[1]);

            WriteLine($"{fileinfo.FullName}");
            WriteLine($"{fileinfo.Name}");

            try
            {
                IPEndPoint clientAddress = new IPEndPoint(0, 0);
                IPEndPoint serverAddress = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);

                WriteLine($"Client : {clientAddress.ToString()}, Server: {serverAddress.ToString()}");

                uint msgId = 0;

                Message reqMsg = new Message();


                reqMsg.Body = new BodyRequest()
                {
                    FILESIZE = new FileInfo(filepath).Length,
                    FILENAME = System.Text.Encoding.Default.GetBytes(filepath)
                };
                reqMsg.Header = new Header()
                {
                    MSGID      = msgId++,
                    MSGTYPE    = CONSTANTS.REQ_FILE_SEND,
                    BODYLEN    = (uint)reqMsg.Body.GetSize(),
                    FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                    LASTMSG    = CONSTANTS.NOT_LASTMSG,
                    SEQ        = 0
                };

                TcpClient client = new TcpClient(clientAddress);
                client.Connect(serverAddress);

                NetworkStream stream = client.GetStream();

                MessageUtil.Send(stream, reqMsg);

                Message rsqMsg = MessageUtil.Receive(stream);

                if (rsqMsg.Header.MSGTYPE != CONSTANTS.REP_FILE_SEND)
                {
                    WriteLine($"정상적인 서버 응답이 아닙니다. {rsqMsg.Header.MSGTYPE}");
                    return;
                }

                if (((BodyResponse)rsqMsg.Body).RESPONSE == CONSTANTS.DENIED)
                {
                    WriteLine("서버에서 파일 전송을 거부했습니다.");
                    return;
                }

                using (Stream fileStream = new FileStream(filepath, FileMode.Open))
                {
                    byte[] rbytes = new byte[CHUNK_SIZE];

                    long readValue = BitConverter.ToInt64(rbytes, 0);

                    int    totalRead  = 0;
                    ushort msgSeq     = 0;
                    byte   fragmented = (fileStream.Length < CHUNK_SIZE) ? CONSTANTS.NOT_FRAGMENTED : CONSTANTS.FRAGMENTED;

                    WriteLine($"FileSender fileStream.Length : {fileStream.Length}");

                    while (totalRead < fileStream.Length)
                    {
                        int read = fileStream.Read(rbytes, 0, CHUNK_SIZE);
                        totalRead += read;
                        Message fileMsg = new Message();

                        byte[] sendBytes = new byte[read];
                        Array.Copy(rbytes, 0, sendBytes, 0, read);

                        fileMsg.Body   = new BodyData(sendBytes);
                        fileMsg.Header = new Header()
                        {
                            MSGID      = msgId,
                            MSGTYPE    = CONSTANTS.FILE_SEND_DATA,
                            BODYLEN    = (uint)fileMsg.Body.GetSize(),
                            FRAGMENTED = CONSTANTS.FRAGMENTED,
                            LASTMSG    = (totalRead < fileStream.Length) ? CONSTANTS.NOT_LASTMSG : CONSTANTS.LASTMSG,
                            SEQ        = msgSeq++
                        };

                        MessageUtil.Send(stream, fileMsg);
                    }
                    WriteLine();
                    Message rstMsg = MessageUtil.Receive(stream);

                    BodyResult result = ((BodyResult)rstMsg.Body);
                    WriteLine($"파일 전송 성공 : {result.RESULT == CONSTANTS.SUCCESS}");
                }
                stream.Close();
                client.Close();
            }
            catch (SocketException e)
            {
                WriteLine(e);
            }
            WriteLine("클라이언트를 종료 합니다.");
        }
예제 #5
0
        private async Task <BodyResult <int, int, BodyFailedItem> > DoBodyAsync(BodySetting bodySettingses)
        {
            Console.WriteLine();
            Console.WriteLine(@"########### Start Of Body OF Stat ############");
            Console.WriteLine();
            Console.WriteLine(@"Body of PortStat job fired.    |    Utc Time: {0}", DateTime.UtcNow.ToLongTimeString());
            Console.WriteLine(@"Params:");
            Console.WriteLine(@"Count of items:    {0}", bodySettingses.Items.Count);
            Console.WriteLine(@"Delay before all items:    {0}ms", bodySettingses.DelayBeforDoingBody);
            Console.WriteLine(@"Delay before each item:    {0}ms", bodySettingses.DelayBeforDoingPerBodyItem_ByWeb);
            Console.WriteLine();
            Console.WriteLine(@"##############################################");
            Console.WriteLine();

            // مکث قبل از انجام بدنه
            await Task.Delay(bodySettingses.DelayBeforDoingBody);

            // لیست موفق‌ها و شکست خورده‌ها
            var successList = new Dictionary <int, int>();
            var failedList  = new List <BodyFailedItem>();

            // حلقه روی آیتم‌های بدنه
            foreach (var bodyItem in bodySettingses.Items.ToList())
            {
                var bodyFailedItem = new BodyFailedItem(bodyItem);
                try
                {
                    // آیا این پورت آیدنتیفایر معتبر دارد؟
                    var hasValid_Identifier = bodyItem.Identifier.HasValue && bodyItem.Identifier.GetValueOrDefault() != 0;
                    // آیا این پورت نام‌کاربری معتبر دارد؟
                    var hasValid_Username = !string.IsNullOrEmpty(bodyItem.Username);

                    // اگر نام‌کاربری یا آیدنتیفایر معتبر داشت
                    if (hasValid_Identifier || hasValid_Username)
                    {
                        // تعداد فالور با مقدار پیش‌فرض آن
                        var portFollowerCount = -1;

                        // اگر نام‌کاربر معتبر دارد
                        if (hasValid_Username)
                        {
                            // مکث قبل از آمارگیری با روش وب
                            await Task.Delay(bodySettingses.DelayBeforDoingPerBodyItem_ByWeb);

                            // خواندن صفحه وب این کانال از روی سایت تلگرام و استخراج اطلاعات از آن
                            TgWebFetch usernameWebPage = TgWebTools.FetchTelegramUserInfoByWeb(bodyItem.Username, -1);

                            // اگر استخراج موفق بود
                            if (usernameWebPage.IsWebFetched)
                            {
                                // اگر نوع کاربر استخراجیکانال عمومی بود
                                if (usernameWebPage.UsernameType == UsernameTypes.Channel)
                                {
                                    portFollowerCount = usernameWebPage.FollowerCount;
                                }
                                else
                                {
                                    // علامت‌گذاری اینکه این آیتم قابل آمارگیری از روش وب نبود
                                    bodyFailedItem.IsNotStatable = true;
                                    // تنظیم نوع نام‌کاربری این کانال
                                    bodyFailedItem.UsernameType = usernameWebPage.UsernameType;
                                }
                            }
                        }

                        if (bodySettingses.TryByBotIfPossible_WhenWebWayFailed &&
                            // اگر آیدنتیفایر معتبر دارد
                            hasValid_Identifier &&
                            // اگر آمارش هنوز رقم منفی (پیش‌فرض قبل از آمارگیری) را نشان میدهد
                            portFollowerCount < 0 &&
                            // اگر علامت غیر‌قابل آمارگیری ندارد
                            !bodyFailedItem.IsNotStatable)
                        {
                            // نکث قبل از آمارگیری به روش بات
                            await Task.Delay(bodySettingses.DelayBeforDoingPerBodyItem_ByBot);

                            var bot    = Bot;
                            var chatId = bodyItem.Identifier.Value;
                            portFollowerCount = await bot.GetChatMembersCountAsync(chatId);
                        }

                        // اگر آمار این کانال هنوز رقم منفی (پیش‌فرض زمان شکست در روش‌های آمارگیری بالا) را نشان میدهد
                        if (portFollowerCount < 0)
                        {
                            // افزودن آیتم جاری به لیست شکست خورده‌ها
                            failedList.Add(bodyFailedItem);
                        }
                        // اگر فالور بزرگتر از 0 داشت
                        else if (portFollowerCount > 0)
                        {
                            // افزودن این آیتم به لیست موفق شده‌ها
                            successList.Add(bodyItem.TelegramPortId, portFollowerCount);
                        }
                        Console.WriteLine();
                        Console.Write($@"Follower count of Port #" + bodyItem.TelegramPortId + " >> " + portFollowerCount);
                        Console.Write(@"    |    ");
                        Console.WriteLine(@"Utc Time: " + DateTime.UtcNow.ToLongTimeString());
                        Console.WriteLine(@"______________________________________________");
                    }
                }
                catch (Exception ex)
                {
                    failedList.Add(bodyFailedItem);
                    Console.WriteLine(bodyItem.TelegramPortId + " >> " + bodyItem.Username.AddFirstAtsign(false));
                    Inf.Utility.WriteError(ex, GetType().Name, MethodBase.GetCurrentMethod().Name, "Th error occured on BODY of get Telegram follower count!");
                }
            }

            var bodyResult = new BodyResult <int, int, BodyFailedItem>(successList, failedList);

            Console.WriteLine();
            Console.WriteLine(@"############ End Of Body OF Stat ############");
            Console.WriteLine();
            Console.WriteLine(@"Body done.    |    Utc Time: {0}", DateTime.UtcNow.ToLongTimeString());
            Console.WriteLine(@"Result:");
            Console.WriteLine(@"Total counts : " + bodySettingses.Items.Count);
            Console.WriteLine(@"Successed Count: :" + bodyResult.SuccessList.Count);
            Console.WriteLine(@"Failed Count: :" + bodyResult.FailedList.Count);
            Console.WriteLine();
            Console.WriteLine(@"##############################################");
            Console.WriteLine();
            return(bodyResult);
        }
예제 #6
0
        void Running()
        {
            try
            {
                IPEndPoint clientAddress = new IPEndPoint(0, 0);
                IPEndPoint serverAddress =
                    new IPEndPoint(IPAddress.Parse(serverIp), serverPort);

                this.Invoke(new MethodInvoker(delegate()
                {
                    Logs = String.Format("클라이언트: {0}, 서버:{1}",
                                         clientAddress.ToString(), serverAddress.ToString());
                    Startbtn.Text = "Stop";
                }));

                Message1 reqMsg = new Message1(); //요청 메세지
                reqMsg.Body = new BodyRequest()
                {
                    FILESIZE = new FileInfo(filepath).Length,
                    FILENAME = Encoding.Default.GetBytes(filepath)
                };
                reqMsg.Header = new Header()
                {
                    MSGID      = msgId++,
                    MSGTYPE    = CONSTANTS.REQ_FILE_SEND,
                    BODYLEN    = (uint)reqMsg.Body.GetSize(),
                    FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                    LASTMSG    = CONSTANTS.LASTMSG,
                    SEQ        = 0
                };

                client = new TcpClient(clientAddress);
                client.Connect(serverAddress);

                //디펜던시 인덱션?
                stream = client.GetStream();
                MessageUtil.Send(stream, reqMsg);              //서버로 전송한 메세지

                Message1 rspMsg = MessageUtil.Receive(stream); //서버로부터 받은 메세지

                if (rspMsg.Header.MSGTYPE != CONSTANTS.REP_FILE_SEND)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        Logs = String.Format("정상적인 서버 응답이 아닙니다.{0}",
                                             rspMsg.Header.MSGTYPE);
                    }));
                    return;
                }

                if (((BodyResponse)rspMsg.Body).RESPONSE == CONSTANTS.DENIED)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        Logs = String.Format("서버에서 파일 전송을 거부했습니다.");
                    }));
                    return;
                }

                using (Stream fileStream = new FileStream(filepath, FileMode.Open)) //파일 전송부분
                {
                    byte[] rbytes = new byte[CHUNK_SIZE];

                    long readValue = BitConverter.ToInt64(rbytes, 0);

                    int    totalRead  = 0;
                    ushort msgSeq     = 0;
                    byte   fragmented =
                        (fileStream.Length < CHUNK_SIZE) ?
                        CONSTANTS.NOT_FRAGMENTED : CONSTANTS.FRAGMENTED;
                    while (totalRead < fileStream.Length)
                    {
                        int read = fileStream.Read(rbytes, 0, CHUNK_SIZE);
                        totalRead += read;
                        Message1 fileMsg = new Message1();

                        byte[] sendBytes = new byte[read];
                        Array.Copy(rbytes, 0, sendBytes, 0, read);

                        fileMsg.Body   = new BodyData(sendBytes);
                        fileMsg.Header = new Header()
                        {
                            MSGID      = msgId,
                            MSGTYPE    = CONSTANTS.FILE_SEND_DATA,
                            BODYLEN    = (uint)fileMsg.Body.GetSize(),
                            FRAGMENTED = fragmented,
                            LASTMSG    = (totalRead < fileStream.Length) ?
                                         CONSTANTS.NOT_LASTMSG :
                                         CONSTANTS.LASTMSG,
                            SEQ = msgSeq++
                        };

                        this.Invoke(new MethodInvoker(delegate()
                        {
                            sendBar.PerformStep();
                        }));

                        MessageUtil.Send(stream, fileMsg);
                    }

                    Message1   rstMsg = MessageUtil.Receive(stream);
                    BodyResult result = ((BodyResult)rstMsg.Body);

                    this.Invoke(new MethodInvoker(delegate()
                    {
                        Logs = String.Format("파일 전송 성공 : {0}",
                                             result.RESULT == CONSTANTS.SUCCESS);
                    }));
                } //end While

                stream.Close();
                client.Close();
            } //end try
            catch (SocketException se)
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    Logs          = String.Format(se.ToString());
                    Startbtn.Text = "Start";
                }));

                booServer = false;
                return;
            }
        }
예제 #7
0
        static void Main(string[] args)
        {
            string    serverIp   = "127.0.0.1";
            const int serverPort = 5452;
            string    filePath   = "sample.jpg";

            try
            {
                IPEndPoint clientAddress = new IPEndPoint(0, 0);
                IPEndPoint serverAddress = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);

                Console.WriteLine("클라이언트: {0}, 서버:{1}", clientAddress.ToString(), serverAddress.ToString());

                uint msgId = 0;

                Message reqMsg = new Message();

                reqMsg.Body = new BodyRequest()
                {
                    FILESIZE = new FileInfo(filePath).Length,
                    FILENAME = Encoding.Default.GetBytes(filePath)
                };

                reqMsg.Header = new Header()
                {
                    MSGID      = msgId++,
                    MSGTYPE    = CONSTANTS.REQ_FILE_SEND,
                    BODYLEN    = (uint)reqMsg.Body.GetSize(),
                    FRAGMENTED = CONSTANTS.NOT_FRANGMENTED,
                    LASTMSG    = CONSTANTS.LASTMSG,
                    SEQ        = 0
                };

                TcpClient client = new TcpClient(clientAddress);
                client.Connect(serverAddress);

                NetworkStream stream = client.GetStream();

                MessageUtil.Send(stream, reqMsg);

                Message rspMsg = MessageUtil.Receive(stream);

                if (rspMsg.Header.MSGTYPE != CONSTANTS.REP_FILE_SEND)
                {
                    Console.WriteLine("정상적인 서버 응답이 아닙니다.{0}", rspMsg.Header.MSGTYPE);

                    return;
                }

                if (((BodyResponse)rspMsg.Body).RESPONSE == CONSTANTS.DENIED)
                {
                    Console.WriteLine("서버에서 파일 전송을 거부했습니다.");
                }

                using (Stream fileStream = new FileStream(filePath, FileMode.Open))
                {
                    byte[] rbytes = new byte[CHUNK_SIZE];

                    long readValue = BitConverter.ToInt64(rbytes, 0);

                    int    totalRead  = 0;
                    ushort msgSeq     = 0;
                    byte   fragmented = (fileStream.Length < CHUNK_SIZE) ? CONSTANTS.NOT_FRANGMENTED : CONSTANTS.FRAGMENTED;

                    while (totalRead < fileStream.Length)
                    {
                        int read = fileStream.Read(rbytes, 0, CHUNK_SIZE);
                        totalRead += read;
                        Message fileMsg = new Message();

                        byte[] sendBytes = new byte[read];

                        Array.Copy(rbytes, 0, sendBytes, 0, read);

                        fileMsg.Body   = new BodyData(sendBytes);
                        fileMsg.Header = new Header()
                        {
                            MSGID      = msgId,
                            MSGTYPE    = CONSTANTS.FILE_SEND_DATA,
                            BODYLEN    = (uint)fileMsg.Body.GetSize(),
                            FRAGMENTED = fragmented,
                            LASTMSG    = (totalRead < fileStream.Length) ? CONSTANTS.NOT_LASTMSG : CONSTANTS.LASTMSG,
                            SEQ        = msgSeq++
                        };

                        Console.Write("@");
                        MessageUtil.Send(stream, fileMsg);
                    }

                    Console.WriteLine();

                    Message rstMsg = MessageUtil.Receive(stream);

                    BodyResult result = ((BodyResult)rstMsg.Body);
                    Console.WriteLine("파일 전송 성공 : {0}", result.RESULT == CONSTANTS.SUCCESS);
                }

                stream.Close();
                client.Close();
            }
            catch (SocketException e)
            {
                Console.WriteLine(e);
            }

            Console.WriteLine("클라이언트를 종료합니다.");
            Console.ReadKey();
        }
        private void FileSender(string filepath)
        {
            const int CHUNK_SIZE = 4096;
            string    serverIp   = getipPath();
            int       serverPort = getPort();

            try
            {
                IPEndPoint clientAddress = new IPEndPoint(IPAddress.Any, 0);
                IPEndPoint serverAddress =
                    new IPEndPoint(IPAddress.Parse(serverIp), serverPort);

                UpdateLogBox("클라이언트 : " + clientAddress.ToString() + ", 서버 : " + serverAddress.ToString());

                uint msgId = 0;

                Message reqMsg = new Message();
                reqMsg.Body = new BodyRequest()
                {
                    FILESIZE = new FileInfo(filepath).Length,
                    FILENAME = System.Text.Encoding.Default.GetBytes(System.IO.Path.GetFileName(filepath))
                };
                reqMsg.Header = new Header()
                {
                    MSGID      = msgId++,
                    MSGTYPE    = CONSTANTS.REQ_FILE_SEND,
                    BODYLEN    = (uint)reqMsg.Body.GetSize(),
                    FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                    LASTMSG    = CONSTANTS.LASTMSG,
                    SEQ        = 0
                };

                TcpClient client = new TcpClient(clientAddress);
                client.Connect(serverAddress);

                NetworkStream stream = client.GetStream();

                MessageUtil.Send(stream, reqMsg);

                Message rspMsg = MessageUtil.Receive(stream);

                if (rspMsg.Header.MSGTYPE != CONSTANTS.REP_FILE_SEND)
                {
                    UpdateLogBox("정상적인 서버 응답이 아닙니다." + rspMsg.Header.MSGTYPE);
                    return;
                }

                if (((BodyResponse)rspMsg.Body).RESPONSE == CONSTANTS.DENIED)
                {
                    UpdateLogBox("서버에서 파일 전송을 거부했습니다.");
                    return;
                }

                using (Stream fileStream = new FileStream(filepath, FileMode.Open))
                {
                    byte[] rbytes = new byte[CHUNK_SIZE];

                    long readValue = BitConverter.ToInt64(rbytes, 0);

                    int    totalRead  = 0;
                    ushort msgSeq     = 0;
                    byte   fragmented =
                        (fileStream.Length < CHUNK_SIZE) ?
                        CONSTANTS.NOT_FRAGMENTED : CONSTANTS.FRAGMENTED;

                    while (totalRead < fileStream.Length)
                    {
                        int read = fileStream.Read(rbytes, 0, CHUNK_SIZE);
                        totalRead += read;
                        Message fileMsg = new Message();

                        byte[] sendBytes = new byte[read];
                        Array.Copy(rbytes, 0, sendBytes, 0, read);

                        fileMsg.Body   = new BodyData(sendBytes);
                        fileMsg.Header = new Header()
                        {
                            MSGID      = msgId,
                            MSGTYPE    = CONSTANTS.FILE_SEND_DATA,
                            BODYLEN    = (uint)fileMsg.Body.GetSize(),
                            FRAGMENTED = fragmented,
                            LASTMSG    = (totalRead < fileStream.Length) ?
                                         CONSTANTS.NOT_LASTMSG :
                                         CONSTANTS.LASTMSG,
                            SEQ = msgSeq++
                        };

                        MessageUtil.Send(stream, fileMsg);
                    }

                    Message rstMsg = MessageUtil.Receive(stream);

                    BodyResult result = ((BodyResult)rstMsg.Body);
                    UpdateLogBox("파일 전송 성공 : " + (result.RESULT == CONSTANTS.SUCCESS));
                }

                stream.Close();
                client.Close();
            }
            catch (SocketException e)
            {
                UpdateLogBox("" + e);
            }

            //UpdateLogBox("파일 전송을 마쳤습니다.");
        }
예제 #9
0
        void FileSend(FileInfo filepath, string saveFolder)
        {
            const int CHUNK_SIZE = 4096;

            if (saveFolder.Length == 0)
            {
                saveFolder = "upload";
            }

            FUP.Message reqMsg = new FUP.Message();

            reqMsg.Body = new BodyRequest()
            {
                FILESIZE   = filepath.Length,
                FOLDERSIZE = saveFolder.Length,
                FILENAME   = System.Text.Encoding.Default.GetBytes(filepath.Name),
                FOLDERNAME = System.Text.Encoding.Default.GetBytes(saveFolder)
            };
            reqMsg.Header = new Header()
            {
                MSGID      = msgId++,
                MSGTYPE    = CONSTANTS.REQ_FILE_SEND,
                BODYLEN    = (uint)reqMsg.Body.GetSize(),
                FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                LASTMSG    = CONSTANTS.NOT_LASTMSG,
                SEQ        = 0
            };
            MessageUtil.Send(stream, reqMsg);

            FUP.Message rsqMsg = MessageUtil.Receive(stream);

            if (rsqMsg.Header.MSGTYPE != CONSTANTS.REP_FILE_SEND)
            {
                lvState.Items.Add($"정상적인 서버 응답이 아닙니다. {rsqMsg.Header.MSGTYPE}");
                ConnectedCheck();
                return;
            }

            if (((BodyResponse)rsqMsg.Body).RESPONSE == CONSTANTS.DENIED)
            {
                lvState.Items.Add("서버에서 파일 전송을 거부했습니다.");
                ConnectedCheck();
                return;
            }

            using (FileStream fileStream = new FileStream(filepath.FullName, FileMode.Open))
            {
                byte[] rbytes = new byte[CHUNK_SIZE];

                long readValue = BitConverter.ToInt64(rbytes, 0);

                int    totalRead  = 0;
                ushort msgSeq     = 0;
                byte   fragmented = (fileStream.Length < CHUNK_SIZE) ? CONSTANTS.NOT_FRAGMENTED : CONSTANTS.FRAGMENTED;


                DateTime startTime = DateTime.Now;
                while (totalRead < fileStream.Length)
                {
                    int read = fileStream.Read(rbytes, 0, CHUNK_SIZE);
                    totalRead += read;
                    FUP.Message fileMsg = new FUP.Message();

                    byte[] sendBytes = new byte[read];
                    Array.Copy(rbytes, 0, sendBytes, 0, read);

                    fileMsg.Body   = new BodyData(sendBytes);
                    fileMsg.Header = new Header()
                    {
                        MSGID      = msgId,
                        MSGTYPE    = CONSTANTS.FILE_SEND_DATA,
                        BODYLEN    = (uint)fileMsg.Body.GetSize(),
                        FRAGMENTED = CONSTANTS.FRAGMENTED,
                        LASTMSG    = (totalRead < fileStream.Length) ? CONSTANTS.NOT_LASTMSG : CONSTANTS.LASTMSG,
                        SEQ        = msgSeq++
                    };
                    MessageUtil.Send(stream, fileMsg);
                }

                FUP.Message rstMsg = MessageUtil.Receive(stream);

                BodyResult result = ((BodyResult)rstMsg.Body);

                TimeSpan resultTime = DateTime.Now - startTime;
                string   RcvResult  = result.RESULT == CONSTANTS.SUCCESS ? "성공" : "실패";

                lvState.Items.Add($"파일 전송 {RcvResult}");
                lvState.Items.Add($"전송 시간 : {resultTime}");
                lvState.Items.Add($"저장 폴더 : {saveFolder}");
            }
        }
예제 #10
0
파일: FUP.cs 프로젝트: penpenguin2018/Army
        public static Message Receive(System.IO.Stream reader)
        {
            int totalRecv  = 0;
            int sizeToRead = 16;

            byte[] hBuffer = new byte[sizeToRead];

            while (sizeToRead > 0)
            {
                byte[] buffer = new byte[sizeToRead];
                int    recv   = reader.Read(buffer, 0, sizeToRead);
                if (recv == 0)
                {
                    return(null);
                }

                buffer.CopyTo(hBuffer, totalRecv);
                totalRecv  += recv;
                sizeToRead -= recv;
            }

            Header header = new Header(hBuffer);

            totalRecv = 0;
            byte[] bBuffer = new byte[header.BODYLEN];
            sizeToRead = (int)header.BODYLEN;

            while (sizeToRead > 0)
            {
                byte[] buffer = new byte[sizeToRead];
                int    recv   = reader.Read(buffer, 0, sizeToRead);
                if (recv == 0)
                {
                    return(null);
                }

                buffer.CopyTo(bBuffer, totalRecv);
                totalRecv  += recv;
                sizeToRead -= recv;
            }

            ISerializable body = null;

            switch (header.MSGTYPE)
            {
            case CONSTANTS.REQ_FILE_SEND:
                body = new BodyRequest(bBuffer);
                break;

            case CONSTANTS.REP_FILE_SEND:
                body = new BodyResponse(bBuffer);
                break;

            case CONSTANTS.FILE_SEND_DATA:
                body = new BodyData(bBuffer);
                break;

            case CONSTANTS.FILE_SEND_RES:
                body = new BodyResult(bBuffer);
                break;

            default:
                throw new System.Exception(System.String.Format("Unknown MSGTYPE : {0}" + header.MSGTYPE));
            }

            return(new Message()
            {
                Header = header, Body = body
            });
        }