Exemple #1
0
        /// <summary>
        /// 获取数据
        /// </summary>
        public JSON.Report.GetData.ReportResponse GetData(BodyRequest bodyData)
        {
            try
            {
                if (this.loginResponse == null || loginResponse.ReturnCode != 0)
                {
                    // 重新登录
                    this.loginResponse = this.login.DoLogin();
                }

                ReportRequest data = new ReportRequest();
                data.Header.AccountType = "1";
                data.Header.Password    = this.loginResponse.ST;
                data.Header.Token       = this.login.Token;
                data.Header.UserName    = this.login.UserName;

                data.Body = bodyData;

                string value = HttpManager.RequestReport(Report.URL + "/getData", this.loginResponse.UCID, data);
                JSON.Report.GetData.ReportResponse response = JsonConvert.DeserializeObject <JSON.Report.GetData.ReportResponse>(value);
                return(response);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (this.loginResponse != null || loginResponse.ReturnCode == 0)
                {
                    // 登出
                    this.login.DoLogout(this.loginResponse.UCID, this.loginResponse.ST);
                }
            }
        }
        public static TokenData tokenData(BodyRequest request, BodyResponse response, int role)
        {
            TokenData tokenData = null;

            if (!Configs.DEBUG_MODE)
            {
                //var thread = new Thread((object t) =>
                //{
                int  times  = 3;
                bool fail   = true;
                var  client = new HttpClient();

                CheckTokenRequest ctRequest = new CheckTokenRequest();
                ctRequest.Token         = request.Token;
                ctRequest.TokenPassword = Configs.TOKEN_PASSWORD;
                ctRequest.Role          = role;

                do
                {
                    try
                    {
                        var result = client.PostAsync(Configs.CHECK_TOKEN, new StringContent(JsonConvert.SerializeObject(ctRequest), Encoding.UTF8, "application/json")).Result.Content.ReadAsAsync <CheckTokenResponse>().Result;
                        fail = result == null;
                        if (!fail)
                        {
                            response.IsTokenTimeout = result.IsTokenTimeout;
                            if (result.IsError)
                            {
                                response.Errors.Add("Không thể truy cập đến máy chủ.");
                                response.IsError = true;
                            }
                            else
                            {
                                tokenData = result.Data;
                            }
                            break;
                        }
                    }
                    catch { }
                } while (fail && --times > 0);
                //(t as Thread).Abort();
                //});
                //thread.Start(thread);
            }
            return(tokenData);
        }
        private static void CallApiAndSave(BodyRequest request)
        {
            var         dic      = GetDicOfAllName();
            BodyRequest para     = null;
            var         clientDb = new MongoDbHelper(Config.MONGODB_CONNECTION, Config.DBName, true, true);

            Parallel.ForEach(dic, item =>
            {
                para        = (BodyRequest)request.Clone();
                para.Method = item.Value;
                var data    = GetData(para);

                //json处理,取值到result节点
                JObject jsonObj = JObject.Parse(data);
                var resultJson  = jsonObj["body"].First.First.First.First.First.ToString();

                //json直接转化成BsonDocument
                BsonDocument document = BsonDocument.Parse(resultJson);
                clientDb.Insert(item.Key, document);
            });
            Console.WriteLine("数据落入mongo完毕");
        }
        /// <summary>
        /// 获取报告
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        private static string GetData(BodyRequest body)
        {
            string url     = Config.API_URL + "/getData";
            var    request = new ReportRequest
            {
                Header = new HeaderRequest
                {
                    AccountType = Config.ACCOUNT_TYPE,
                    Password    = Config.PASSWORD,
                    Token       = Config.TOKEN,
                    UserName    = Config.USERNAME
                },
                Body = body
            };
            var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(request);
            var message     = HttpHelper.PostHttps(url, requestJson);

            //json中数据有很多空数组,反序列化需要特殊处理
            //目前ReportResponse反序列化失败,需要针对methodName单独写实体类
            //var reault = Newtonsoft.Json.JsonConvert.DeserializeObject<ReportResponse>(message);
            return(message);
        }
        static void Main(string[] args)
        {
            var siteList = GetSiteList();
            int siteId   = siteList.Body.Data[0].List[0].SiteId;          //siteId是固定的,调用一次就可以了

            var reqeust = new BodyRequest
            {
                StartDate = "20181223",
                EndDate   = System.DateTime.Now.AddDays(1).ToString("yyyyMMdd"),

                MaxResults = 20,                //0-全部
                StartIndex = 0,

                SiteId = siteId,

                //Method = "visit/toppage/a" //要调用的报告的名称,根据文档写
            };

            Console.WriteLine("正在进行 数据查询 和 落库 中 。。。");
            Console.WriteLine("请稍等 。。。");
            CallApiAndSave(reqeust);
            Console.ReadKey();
        }
Exemple #6
0
        public static string doPostJSON(BodyRequest JSONObject)
        {
            var responseResult = "";
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3000/quebec/demandes/");

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = JsonConvert.SerializeObject(JSONObject);

                streamWriter.Write(json);
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                responseResult = streamReader.ReadToEnd();
            }

            return(responseResult);
        }
Exemple #7
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("사용법 : {0} <Directory>", Process.GetCurrentProcess().ProcessName);
                return;
            }
            uint msgId = 0;

            string dir = args[0];

            if (Directory.Exists(dir) == false)
            {
                Directory.CreateDirectory(dir);
            }

            const int   bindPort = 5425;
            TcpListener server   = null;

            try
            {
                IPEndPoint localAddress = new IPEndPoint(0, bindPort);

                server = new TcpListener(localAddress);
                server.Start();

                Console.WriteLine("파일 업로드 서버 시작...");

                while (true)
                {
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("클라이언트 접속 : {0}", ((IPEndPoint)client.Client.RemoteEndPoint).ToString());

                    NetworkStream stream = client.GetStream();

                    Message reqMsg = MessageUtil.Receive(stream);

                    if (reqMsg.Header.MSGTYPE != CONSTANTS.REQ_FILE_SEND)
                    {
                        stream.Close();
                        client.Close();
                        continue;
                    }

                    BodyRequest reqBody = (BodyRequest)reqMsg.Body;

                    Console.WriteLine("파일 업로드 요청이 왔습니다. 수락하시겠습니까? yes/no");
                    string answer = Console.ReadLine();

                    Message rspMsg = new Message();
                    rspMsg.Body = new BodyResponse()
                    {
                        MSGID    = reqMsg.Header.MSGID,
                        RESPONSE = CONSTANTS.ACCEPTED
                    };
                    rspMsg.Header = new Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = CONSTANTS.REP_FILE_SEND,
                        BODYLEN    = (uint)rspMsg.Body.GetSize(),
                        FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                        LASTMSG    = CONSTANTS.LASTMSG,
                        SEQ        = 0
                    };

                    if (answer != "yes")
                    {
                        rspMsg.Body = new BodyResponse()
                        {
                            MSGID    = reqMsg.Header.MSGID,
                            RESPONSE = CONSTANTS.DENIED
                        };

                        MessageUtil.Send(stream, rspMsg);
                        stream.Close();
                        client.Close();

                        continue;
                    }

                    else
                    {
                        MessageUtil.Send(stream, rspMsg);
                    }

                    Console.WriteLine("파일 전송을 시작합니다...");

                    long       fileSize = reqBody.FILESIZE;
                    string     fileName = Encoding.Default.GetString(reqBody.FILENAME);
                    FileStream file     = new FileStream(dir + "\\" + fileName, FileMode.Create);

                    uint?  dataMsgId = null;
                    ushort prevSeq   = 0;
                    while ((reqMsg = MessageUtil.Receive(stream)) != null)
                    {
                        Console.Write("#");
                        if (reqMsg.Header.MSGTYPE != CONSTANTS.FILE_SEND_DATA)
                        {
                            break;
                        }

                        if (dataMsgId == null)
                        {
                            dataMsgId = reqMsg.Header.MSGID;
                        }
                        else
                        {
                            if (dataMsgId != reqMsg.Header.MSGID)
                            {
                                break;
                            }
                        }

                        if (prevSeq++ != reqMsg.Header.SEQ)
                        {
                            Console.WriteLine("{0}, {1}", prevSeq, reqMsg.Header.SEQ);
                            break;
                        }

                        file.Write(reqMsg.Body.GetBytes(), 0, reqMsg.Body.GetSize());

                        if (reqMsg.Header.FRAGMENTED == CONSTANTS.NOT_FRAGMENTED)
                        {
                            break;
                        }
                        if (reqMsg.Header.LASTMSG == CONSTANTS.LASTMSG)
                        {
                            break;
                        }
                    }

                    long recvFileSize = file.Length;
                    file.Close();

                    Console.WriteLine();
                    Console.WriteLine("수신 파일 크기 : {0} bytes", recvFileSize);

                    Message rstMsg = new Message();
                    rstMsg.Body = new BodyResult()
                    {
                        MSGID  = reqMsg.Header.MSGID,
                        RESULT = CONSTANTS.SUCCESS
                    };
                    rstMsg.Header = new Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = CONSTANTS.FILE_SEND_RES,
                        BODYLEN    = (uint)rstMsg.Body.GetSize(),
                        FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                        LASTMSG    = CONSTANTS.LASTMSG,
                        SEQ        = 0
                    };

                    if (fileSize == recvFileSize)
                    {
                        MessageUtil.Send(stream, rstMsg);
                    }
                    else
                    {
                        rstMsg.Body = new BodyResult()
                        {
                            MSGID  = reqMsg.Header.MSGID,
                            RESULT = CONSTANTS.FAIL
                        };

                        MessageUtil.Send(stream, rstMsg);
                    }
                    Console.WriteLine("파일 전송을 마쳤습니다.");

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

            Console.WriteLine("서버를 종료합니다.");
        }
Exemple #8
0
        public void FileReceive()
        {
            while (true)
            {
                FUP.Message reqMsg = MessageUtil.Receive(client.stream);

                if (reqMsg.Header.MSGTYPE == CONSTANTS.CONNECT_STATE_CHECK)
                {
                    BodyCheck body = (BodyCheck)reqMsg.Body;
                    if (body.STATE == CONSTANTS.DISCONNECT)
                    {
                        CloseEvent();
                        continue;
                    }
                }

                if (reqMsg.Header.MSGTYPE != CONSTANTS.REQ_FILE_SEND)
                {
                    CloseEvent();
                    continue;
                }

                BodyRequest reqBody = (BodyRequest)reqMsg.Body;

                var anwser = MessageBox.Show("파일 업로드 요청이 들어왔습니다. 수락하시겠습니까? Yes / No : ",
                                             "파일 업로드 요청", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

                FUP.Message rspMsg = new FUP.Message();
                rspMsg.Body = new BodyResponse()
                {
                    MSGID    = reqMsg.Header.MSGID,
                    RESPONSE = CONSTANTS.ACCEPTED
                };
                rspMsg.Header = new Header()
                {
                    MSGID      = msgId++,
                    MSGTYPE    = CONSTANTS.REP_FILE_SEND,
                    BODYLEN    = (uint)rspMsg.Body.GetSize(),
                    FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                    LASTMSG    = CONSTANTS.NOT_LASTMSG,
                    SEQ        = 0
                };

                if (anwser == DialogResult.No)
                {
                    rspMsg.Body = new BodyResponse()
                    {
                        MSGID    = reqMsg.Header.MSGID,
                        RESPONSE = CONSTANTS.DENIED
                    };

                    MessageUtil.Send(client.stream, rspMsg);

                    CloseEvent();
                    continue;
                }
                else
                {
                    MessageUtil.Send(client.stream, rspMsg);
                }

                lvServState.Items.Add("파일 전송을 시작합니다.");

                long   fileSize   = reqBody.FILESIZE;
                string fileName   = Encoding.Default.GetString(reqBody.FILENAME);
                string saveFolder = Encoding.Default.GetString(reqBody.FOLDERNAME);
                string saveDir    = "";

                if (directory.Length == 0)
                {
                    saveDir = Directory.GetCurrentDirectory();
                    saveDir = saveDir + "\\" + saveFolder;
                }
                else
                {
                    saveDir = directory + "\\" + saveFolder;
                }

                if (Directory.Exists(saveDir) == false)
                {
                    Directory.CreateDirectory(saveDir);
                }

                FileStream file = new FileStream(saveDir + "\\" + fileName, FileMode.Create);

                uint?  dataMsgId = null;
                ushort prevSeq   = 0;
                while ((reqMsg = MessageUtil.Receive(client.stream)) != null)
                {
                    if (reqMsg.Header.MSGTYPE != CONSTANTS.FILE_SEND_DATA)
                    {
                        break;
                    }
                    if (dataMsgId == null)
                    {
                        dataMsgId = reqMsg.Header.MSGID;
                    }
                    else
                    {
                        if (dataMsgId != reqMsg.Header.MSGID)
                        {
                            break;
                        }
                    }
                    if (prevSeq++ != reqMsg.Header.SEQ)
                    {
                        lvServState.Items.Add($"{prevSeq}, {reqMsg.Header.SEQ}");
                        break;
                    }

                    file.Write(reqMsg.Body.GetBytes(), 0, reqMsg.Body.GetSize());

                    if (reqMsg.Header.FRAGMENTED == CONSTANTS.NOT_FRAGMENTED)
                    {
                        break;
                    }
                    if (reqMsg.Header.LASTMSG == CONSTANTS.LASTMSG)
                    {
                        break;
                    }
                }

                long recvFileSize = file.Length;
                file.Close();

                lvServState.Items.Add("");
                lvServState.Items.Add($"수신 파일 크기 {recvFileSize} bytes");

                FUP.Message rstMsg = new FUP.Message();
                rstMsg.Body = new BodyResult()
                {
                    MSGID  = reqMsg.Header.MSGID,
                    RESULT = CONSTANTS.SUCCESS
                };
                rstMsg.Header = new Header()
                {
                    MSGID      = msgId++,
                    MSGTYPE    = CONSTANTS.FILE_SEND_RES,
                    BODYLEN    = (uint)rstMsg.Body.GetSize(),
                    FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                    LASTMSG    = CONSTANTS.LASTMSG,
                    SEQ        = 0
                };
                if (fileSize == recvFileSize)
                {
                    MessageUtil.Send(client.stream, rstMsg);
                }
                else
                {
                    rstMsg.Body = new BodyResult()
                    {
                        MSGID  = reqMsg.Header.MSGID,
                        RESULT = CONSTANTS.FAIL
                    };
                    MessageUtil.Send(client.stream, rstMsg);
                }
                lvServState.Items.Add("파일 전송을 마쳤습니다.");
            }
        }
Exemple #9
0
        static void Main(string[] args)
        {
            args = new string[1] {
                @"C:\Temp"
            };

            if (args.Length < 1)
            {
                Console.WriteLine("Usage : {0} <Directoryy>", Process.GetCurrentProcess().ProcessName);
                return;
            }

            uint msgId = 0;

            string dir = args[0];

            if (Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            const int   bindPort = 5425;
            TcpListener server   = null;



            try
            {
                IPEndPoint localAddress = new IPEndPoint(IPAddress.Parse("192.168.11.45"), bindPort);
                server = new TcpListener(localAddress);
                server.Start();
                Console.WriteLine("Upload server is started");

                while (true)
                {
                    TcpClient clinet = server.AcceptTcpClient();
                    Console.WriteLine("client is connected  : {0}", ((IPEndPoint)clinet.Client.RemoteEndPoint).ToString());

                    NetworkStream stream = clinet.GetStream();


                    // Head (Msg ID , Msg Type , Body Len , Gragment , LastMsg , SEQ ) + Body
                    Message reqMsg = MessageUtil.Receive(stream);         // return request instance from stream.

                    if (reqMsg.Header.MSGTYPE != CONSTANTS.REQ_FILE_SEND) // if not file request. just close and wait new connection.
                    {
                        stream.Close();
                        clinet.Close();
                        continue;
                    }

                    BodyRequest reqbody = (BodyRequest)reqMsg.Body;
                    Console.Write("File Upload is Requested. Yes / No");
                    string answer = Console.ReadLine();

                    Message rspMsg = new Message();
                    rspMsg.Body = new BodyResponse()
                    {
                        MSGID    = reqMsg.Header.MSGID,
                        RESPONSE = CONSTANTS.ACCEPTED
                    };

                    rspMsg.Header = new Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = CONSTANTS.REP_FILE_SEND,
                        BODYLEN    = (uint)rspMsg.Body.GetSize(),
                        FRAGMENTED = CONSTANTS.NOT_FRAGMENT,
                        LASTMSG    = CONSTANTS.LASTMSG,
                        SEQ        = 0
                    }; // Here is definition of response

                    if (answer != "yes")
                    {
                        rspMsg.Body = new BodyResponse()
                        {
                            MSGID    = reqMsg.Header.MSGID,
                            RESPONSE = CONSTANTS.DENIED
                        };                                //if answer is no, response msg body is changed

                        MessageUtil.Send(stream, rspMsg); // send respon msg
                        stream.Close();
                        clinet.Close();
                        continue;
                    }
                    else
                    {
                        MessageUtil.Send(stream, rspMsg);
                    }

                    Console.WriteLine("Transfer is starting");

                    long       fileSize = reqbody.FILESIZE;
                    string     filename = Path.GetFileName(Encoding.Default.GetString(reqbody.FILENAME));
                    FileStream file     = new FileStream(dir + "\\" + filename, FileMode.Create);

                    uint?  dataMsgId = null;
                    ushort prevSeq   = 0;

                    while ((reqMsg = MessageUtil.Receive(stream)) != null)
                    {
                        Console.Write("#");
                        if (reqMsg.Header.MSGTYPE != CONSTANTS.FILE_SEND_DATA)
                        {
                            break;
                        }

                        if (dataMsgId == null)
                        {
                            dataMsgId = reqMsg.Header.MSGID;
                        }
                        else
                        {
                            if (dataMsgId != reqMsg.Header.MSGID)
                            {
                                break;
                            }
                        }

                        if (prevSeq++ != reqMsg.Header.SEQ)
                        {
                            Console.WriteLine("{0} , {1}", prevSeq, reqMsg.Header.SEQ);
                            break;
                        }

                        file.Write(reqMsg.Body.GetByte(), 0, reqMsg.Body.GetSize());

                        if (reqMsg.Header.FRAGMENTED == CONSTANTS.NOT_FRAGMENT)
                        {
                            break;
                        }

                        if (reqMsg.Header.LASTMSG == CONSTANTS.LASTMSG)
                        {
                            break;
                        }
                    }

                    long recvFileSzie = file.Length;
                    file.Close();
                    Console.WriteLine();
                    Console.WriteLine(" Recived File Size : {0} byte", recvFileSzie);

                    Message rstMsg = new Message();
                    rstMsg.Body = new BodyResult()
                    {
                        MSGID  = reqMsg.Header.MSGID,
                        RESULT = CONSTANTS.SUCCESS
                    };

                    rstMsg.Header = new Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = CONSTANTS.FILE_SEND_RES,
                        BODYLEN    = (uint)rstMsg.Body.GetSize(),
                        FRAGMENTED = CONSTANTS.NOT_FRAGMENT,
                        LASTMSG    = CONSTANTS.LASTMSG,
                        SEQ        = 0
                    };

                    if (fileSize == recvFileSzie)
                    {
                        MessageUtil.Send(stream, rstMsg);
                    }
                    else
                    {
                        rstMsg.Body = new BodyResult()
                        {
                            MSGID  = reqMsg.Header.MSGID,
                            RESULT = CONSTANTS.FAIL
                        };

                        MessageUtil.Send(stream, rspMsg);
                    }
                    Console.WriteLine("File Transfer is finished");

                    stream.Close();
                    clinet.Close();
                }
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                server.Stop();
            }
            Console.WriteLine("Sercer is closed");
        }
Exemple #10
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("사용법 : {0} <Directory>", Process.GetCurrentProcess().ProcessName);
                return;
            }
            uint msgId = 0;

            string dir = args[0]; //경로가 없으면 만들자

            if (Directory.Exists(dir) == false)
            {
                Directory.CreateDirectory(dir);
            }

            const int   bindPort = 5425; //정의해놓은 서버 포트
            TcpListener server   = null;

            try
            {
                //IP주소를 0으로 입력하면 127.0.0.1뿐만 아니라 OS에 할당되어 있는 어떤 주소로도 서버에 접속이 가능
                IPEndPoint localAddress = new IPEndPoint(0, bindPort);

                server = new TcpListener(localAddress);
                server.Start();

                Console.WriteLine("파일 업로드 서버 시작...");

                while (true)
                {
                    //클라이언트가 접속하는걷을 받기 위해 대기
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("클라이언트 접속 : {0}", ((IPEndPoint)client.Client.RemoteEndPoint).ToString());

                    //스트림을 통해 읽고 쓰기 수행
                    NetworkStream stream = client.GetStream();
                    Message       reqMsg = MessageUtil.Receive(stream);

                    //파일 전송 요청이 아니면 넘기기
                    if (reqMsg.Header.MSGTYPE != CONSTANTS.REQ_FILE_SEND)
                    {
                        stream.Close();
                        client.Close();
                        continue;
                    }

                    BodyRequest reqBody = (BodyRequest)reqMsg.Body;

                    Console.WriteLine("파일 업로드 요청이 왔습니다. 수락하시겠습니까? yes/no");
                    string answer = Console.ReadLine();

                    Message rspMsg = new Message();
                    rspMsg.Body = new BodyResponse()  //파일 전송 요청에 사용할 응답
                    {
                        MSGID    = reqMsg.Header.MSGID,
                        RESPONSE = CONSTANTS.ACCEPTED
                    };

                    rspMsg.Header = new Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = CONSTANTS.REP_FILE_SEND,
                        BODYLEN    = (uint)rspMsg.Body.GetSize(), //4+1 = 5;
                        FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,    //분할될 일이 없음
                        LASTMSG    = CONSTANTS.LASTMSG,           //마지막 메시지이긴 하니까
                        SEQ        = 0
                    };

                    if (answer != "yes")  //파일 전송 요청 거절
                    {
                        //거절하면 클라이언트에 거부 응답 보냄
                        //요청 메시지의 바디 구조 : MSGID(4바이트), 파일 전송 승인 여부 RESPONSE(1)
                        rspMsg.Body = new BodyResponse()
                        {
                            MSGID    = reqMsg.Header.MSGID,
                            RESPONSE = CONSTANTS.DENIED
                        };
                        MessageUtil.Send(stream, rspMsg);
                        stream.Close();
                        client.Close();

                        continue;
                    }
                    else
                    {
                        MessageUtil.Send(stream, rspMsg); //승낙 메시지 전송
                    }
                    Console.WriteLine("파일 전송을 시작합니다...");

                    long       fileSize = reqBody.FILESIZE;
                    string     fileName = Encoding.Default.GetString(reqBody.FILENAME);
                    FileStream file     = new FileStream(dir + "\\" + fileName, FileMode.Create); //업로드 파일 스트림 생성

                    uint?  dataMsgId = null;
                    ushort prevSeq   = 0;
                    while ((reqMsg = MessageUtil.Receive(stream)) != null)
                    {
                        Console.Write("#");
                        if (reqMsg.Header.MSGTYPE != CONSTANTS.FILE_SEND_DATA)
                        {
                            break;
                        }

                        if (dataMsgId == null) //초기 메시지ID 세팅
                        {
                            dataMsgId = reqMsg.Header.MSGID;
                        }
                        else
                        if (dataMsgId != reqMsg.Header.MSGID)
                        {
                            break;
                        }

                        //메시지 순서가 어긋나면 전송을 중단
                        if (prevSeq++ != reqMsg.Header.SEQ)
                        {
                            Console.WriteLine("{0}, {1}", prevSeq, reqMsg.Header.SEQ);
                            break;
                        }

                        //전송받은 스트림을 서버에서 생성한 파일에 기록
                        file.Write(reqMsg.Body.GetBytes(), 0, reqMsg.Body.GetSize());

                        //분할 메시지가 아니라면 반복을 한번만 하고 빠져나온다
                        //if (reqMsg.Header.FRAGMENTED == CONSTANTS.NOT_FRAGMENTED)
                        //    break;
                        //마지막 메시지면 반복문을 빠져나온다
                        if (reqMsg.Header.LASTMSG == CONSTANTS.LASTMSG)
                        {
                            break;
                        }
                    }

                    long recvFileSize = file.Length;
                    file.Close();

                    Console.WriteLine();
                    Console.WriteLine("수신 파일 크기 : {0} bytes", recvFileSize);

                    //결과를 주는 메시지
                    Message rstMsg = new Message();
                    rstMsg.Body = new BodyResult()
                    {
                        MSGID  = reqMsg.Header.MSGID,
                        RESULT = CONSTANTS.SUCCESS
                    };
                    rstMsg.Header = new Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = CONSTANTS.FILE_SEND_RES,
                        BODYLEN    = (uint)rstMsg.Body.GetSize(),
                        FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                        LASTMSG    = CONSTANTS.LASTMSG,
                        SEQ        = 0
                    };

                    //전송 요청에 담겨온 크기와 실제로 받은 크기를 비교하여 같으면 성공 메시지 보냄
                    if (fileSize == recvFileSize)
                    {
                        MessageUtil.Send(stream, rstMsg);
                    }
                    else
                    {
                        rstMsg.Body = new BodyResult()
                        {
                            MSGID  = reqMsg.Header.MSGID,
                            RESULT = CONSTANTS.FAIL
                        };
                        //파일 크기에 이상이 있으면 실패 메시지 보냄
                        MessageUtil.Send(stream, rstMsg);
                    }

                    Console.WriteLine("파일 전송을 마쳤습니다.");

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

            Console.WriteLine("서버를 종료합니다.");
        }
        private void startServer()
        {
            uint msgId = 0;

            int bindPort = getPort();

            string      clientIP = null;
            TcpListener server   = null;

            try
            {
                IPEndPoint localAddress = new IPEndPoint(IPAddress.Any, bindPort);

                server = new TcpListener(localAddress);
                server.Start();

                UpdateLogBox("파일 업로드 서버 시작... ");
                UpdateLogBox("현재 포트번호 : " + bindPort);

                while (this.isServerAlive)
                {
                    TcpClient client      = server.AcceptTcpClient();
                    string    connectedIP = ((IPEndPoint)client.Client.RemoteEndPoint).ToString();

                    UpdateLogBox("클라이언트 접속 : " + connectedIP);

                    NetworkStream stream = client.GetStream();

                    Message reqMsg = MessageUtil.Receive(stream);

                    if (reqMsg.Header.MSGTYPE != CONSTANTS.REQ_FILE_SEND)
                    {
                        stream.Close();
                        client.Close();
                        continue;
                    }

                    BodyRequest reqBody = (BodyRequest)reqMsg.Body;

                    Message rspMsg = new Message();
                    rspMsg.Body = new BodyResponse()
                    {
                        MSGID    = reqMsg.Header.MSGID,
                        RESPONSE = CONSTANTS.ACCEPTED
                    };
                    rspMsg.Header = new Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = CONSTANTS.REP_FILE_SEND,
                        BODYLEN    = (uint)rspMsg.Body.GetSize(),
                        FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                        LASTMSG    = CONSTANTS.LASTMSG,
                        SEQ        = 0
                    };

                    if (clientIP == null) // 같은 IP에서 보낸 경우 한번만 승낙하면 되게
                    {
                        MessageBoxResult result = MessageBox.Show(connectedIP.Substring(0, 12) + "으로 부터 파일 업로드 요청이 왔습니다. 수락하시겠습니까?", "파일 업로드 요청", MessageBoxButton.OKCancel);

                        if (result == MessageBoxResult.OK)
                        {
                            UpdateLogBox("파일 전송을 시작합니다... ");
                            MessageUtil.Send(stream, rspMsg);
                            clientIP = connectedIP.Substring(0, 12);
                        }
                        else
                        {
                            rspMsg.Body = new BodyResponse()
                            {
                                MSGID    = reqMsg.Header.MSGID,
                                RESPONSE = CONSTANTS.DENIED
                            };
                            MessageUtil.Send(stream, rspMsg);
                            stream.Close();
                            client.Close();
                            UpdateLogBox("파일 전송을 거절했습니다.");

                            continue;
                        }
                    }
                    else
                    {
                        UpdateLogBox("파일 전송을 시작합니다... ");
                        MessageUtil.Send(stream, rspMsg);
                    }


                    long   fileSize = reqBody.FILESIZE;
                    string fileName = Encoding.Default.GetString(reqBody.FILENAME);

                    String curSaveLoc = getFolderPath();
                    curSaveLoc = curSaveLoc + @"\download";
                    DirectoryInfo di = new DirectoryInfo(curSaveLoc);

                    if (di.Exists == false)
                    {
                        di.Create(); // download 폴더 생성
                    }

                    FileStream file =
                        new FileStream(curSaveLoc + "\\" + fileName, FileMode.Create);

                    uint?dataMsgId = null;
                    int  prevSeq   = 0;
                    while ((reqMsg = MessageUtil.Receive(stream)) != null)
                    {
                        if (reqMsg.Header.MSGTYPE != CONSTANTS.FILE_SEND_DATA)
                        {
                            break;
                        }

                        if (dataMsgId == null)
                        {
                            dataMsgId = reqMsg.Header.MSGID;
                        }
                        else
                        {
                            if (dataMsgId != reqMsg.Header.MSGID)
                            {
                                break;
                            }
                        }

                        if (prevSeq++ != reqMsg.Header.SEQ) // 메세지 순서가 어긋나면 전송 중단
                        {
                            UpdateLogBox("" + prevSeq + reqMsg.Header.SEQ);
                            break;
                        }

                        file.Write(reqMsg.Body.GetBytes(), 0, reqMsg.Body.GetSize()); // 전송받은 스트림을 생성한 파일에 기록

                        if (reqMsg.Header.LASTMSG == CONSTANTS.LASTMSG)               // 마지막 메세지라면 반복문 종료
                        {
                            break;
                        }
                    }

                    long recvFileSize = file.Length;
                    file.Close();

                    UpdateLogBox("수신 파일 크기 : " + recvFileSize + "bytes");

                    Message rstMsg = new Message();
                    rstMsg.Body = new BodyResult()
                    {
                        MSGID  = reqMsg.Header.MSGID,
                        RESULT = CONSTANTS.SUCCESS
                    };
                    rstMsg.Header = new Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = CONSTANTS.FILE_SEND_RES,
                        BODYLEN    = (uint)rstMsg.Body.GetSize(),
                        FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                        LASTMSG    = CONSTANTS.LASTMSG,
                        SEQ        = 0
                    };

                    if (fileSize == recvFileSize)
                    {
                        MessageUtil.Send(stream, rstMsg);
                    }
                    else
                    {
                        rstMsg.Body = new BodyResult()
                        {
                            MSGID  = reqMsg.Header.MSGID,
                            RESULT = CONSTANTS.FAIL
                        };

                        MessageUtil.Send(stream, rstMsg);
                    }
                    UpdateLogBox("파일 전송을 마쳤습니다.");

                    stream.Close();
                    client.Close();
                }
            }
            catch (SocketException e)
            {
                UpdateLogBox("" + e);
            }
            finally
            {
                server.Stop();
                this.isServerAlive = true;
                serverManagement(true);
            }
        }
Exemple #12
0
        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
            });
        }
Exemple #13
0
        void Running()
        {
            try
            {
                IPEndPoint localAddress =
                    new IPEndPoint(0, bindPort);        //0 => 컴퓨터 내에 할당된 어느 주소로 접근해도 서버에 접속 가능

                server = new TcpListener(localAddress); //
                server.Start();

                this.Invoke(new MethodInvoker(delegate()
                {
                    IpText.Enabled = false;
                    Logs           = String.Format("Server Open...");
                    Serverbtn.Text = "Stop";
                }));

                while (true) //
                {
                    client = server.AcceptTcpClient();

                    this.Invoke(new MethodInvoker(delegate()
                    {
                        Logs = String.Format("클라이언트 접속 : {0} ",
                                             ((IPEndPoint)client.Client.RemoteEndPoint).ToString());
                    }));

                    stream = client.GetStream();

                    Message1 reqMsg = MessageUtil.Receive(stream);

                    if (reqMsg.Header.MSGTYPE != CONSTANTS.REQ_FILE_SEND)
                    {
                        stream.Close();
                        client.Close();
                        continue;
                    }

                    BodyRequest reqBody = (BodyRequest)reqMsg.Body;

                    this.Invoke(new MethodInvoker(delegate()
                    {
                        if (MessageBox.Show("파일 업로드 요청이 왔습니다. 수락하시겠습니까?", "알림 메세지", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            answer = "yes";
                        }
                    }));

                    Message1 rspMsg = new Message1();
                    rspMsg.Body = new BodyResponse()
                    {
                        MSGID    = reqMsg.Header.MSGID,
                        RESPONSE = CONSTANTS.ACCEPTED
                    };
                    rspMsg.Header = new Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = CONSTANTS.REP_FILE_SEND,
                        BODYLEN    = (uint)rspMsg.Body.GetSize(),
                        FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                        LASTMSG    = CONSTANTS.LASTMSG,
                        SEQ        = 0
                    };

                    if (answer != "yes")
                    {
                        rspMsg.Body = new BodyResponse()
                        {
                            MSGID    = reqMsg.Header.MSGID,
                            RESPONSE = CONSTANTS.DENIED
                        };
                        MessageUtil.Send(stream, rspMsg);
                        stream.Close();
                        client.Close();

                        continue;
                    }
                    else
                    {
                        MessageUtil.Send(stream, rspMsg);
                    }

                    this.Invoke(new MethodInvoker(delegate()
                    {
                        Logs = String.Format("파일 전송을 시작합니다...");
                    }));

                    long       fileSize = reqBody.FILESIZE;
                    string     fileName = Encoding.Default.GetString(reqBody.FILENAME);
                    FileStream file     =
                        new FileStream(dir + "\\" + fileName, FileMode.Create);

                    uint?  dataMsgId = null;
                    ushort prevSeq   = 0;
                    while ((reqMsg = MessageUtil.Receive(stream)) != null)
                    {
                        this.Invoke(new MethodInvoker(delegate()
                        {
                            ReceiveBar.PerformStep();
                        }));
                        if (reqMsg.Header.MSGTYPE != CONSTANTS.FILE_SEND_DATA)
                        {
                            break;
                        }

                        if (dataMsgId == null)
                        {
                            dataMsgId = reqMsg.Header.MSGID;
                        }
                        else
                        {
                            if (dataMsgId != reqMsg.Header.MSGID)
                            {
                                break;
                            }
                        }

                        if (prevSeq++ != reqMsg.Header.SEQ)
                        {
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                Logs = String.Format("{0}, {1}", prevSeq, reqMsg.Header.SEQ);
                            }));
                            break;
                        }

                        file.Write(reqMsg.Body.GetBytes(), 0, reqMsg.Body.GetSize());

                        if (reqMsg.Header.LASTMSG == CONSTANTS.LASTMSG)
                        {
                            break;
                        }
                    }

                    long recvFileSize = file.Length;
                    file.Close();

                    this.Invoke(new MethodInvoker(delegate()
                    {
                        Logs = String.Format("수신 파일 크기 : {0} bytes", recvFileSize);
                    }));

                    Message1 rstMsg = new Message1();
                    rstMsg.Body = new BodyResult()
                    {
                        MSGID  = reqMsg.Header.MSGID,
                        RESULT = CONSTANTS.SUCCESS
                    };
                    rstMsg.Header = new Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = CONSTANTS.FILE_SEND_RES,
                        BODYLEN    = (uint)rstMsg.Body.GetSize(),
                        FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                        LASTMSG    = CONSTANTS.LASTMSG,
                        SEQ        = 0
                    };

                    if (fileSize == recvFileSize)
                    {
                        MessageUtil.Send(stream, rstMsg);
                    }
                    else
                    {
                        rstMsg.Body = new BodyResult()
                        {
                            MSGID  = reqMsg.Header.MSGID,
                            RESULT = CONSTANTS.FAIL
                        };

                        MessageUtil.Send(stream, rstMsg);
                    }

                    this.Invoke(new MethodInvoker(delegate()
                    {
                        Logs = String.Format("파일 전송을 마쳤습니다...");
                    }));

                    stream.Close();
                    client.Close();
                } //end While
            }     // end try
            catch
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    if (mainTh.IsAlive)
                    {
                        Logs = String.Format("쓰레드 종료중...");
                        return;
                    }
                }));

                booServer = false;
                return;
            }
        }
Exemple #14
0
        static void Main(string[] args)
        {
            uint msgId = 0;

            const int bindPort = 5425;

            TcpListener server = null;

            try
            {
                IPEndPoint localAddress = new IPEndPoint(0, bindPort);

                server = new TcpListener(localAddress);
                server.Start();

                WriteLine("파일 업로드 서버 시작... ");

                Client fileClient = null;

                bool ClientLock = false;

                while (true)
                {
                    if (!ClientLock)
                    {
                        fileClient = new Client(server);

                        ClientLock = true;
                    }

                    Message reqMsg = MessageUtil.Receive(fileClient.stream);

                    if (reqMsg.Header.MSGTYPE == CONSTANTS.CONNECT_STATE_CHECK)
                    {
                        BodyCheck checkBody = (BodyCheck)reqMsg.Body;
                        if (checkBody.STATE == CONSTANTS.DISCONNECT)
                        {
                            ClientClose(fileClient);
                            ClientLock = false;
                            continue;
                        }
                    }

                    if (reqMsg.Header.MSGTYPE != CONSTANTS.REQ_FILE_SEND)
                    {
                        ClientClose(fileClient);
                        ClientLock = false;
                        continue;
                    }

                    BodyRequest reqBody = (BodyRequest)reqMsg.Body;

                    Write("파일 업로드 요청이 들어왔습니다. 수락하시겠습니까? Yes / No : ");
                    string answer = ReadLine();

                    Message rspMsg = new Message();
                    rspMsg.Body = new BodyResponse()
                    {
                        MSGID    = reqMsg.Header.MSGID,
                        RESPONSE = CONSTANTS.ACCEPTED
                    };
                    rspMsg.Header = new Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = CONSTANTS.REP_FILE_SEND,
                        BODYLEN    = (uint)rspMsg.Body.GetSize(),
                        FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                        LASTMSG    = CONSTANTS.NOT_LASTMSG,
                        SEQ        = 0
                    };

                    if (answer != "Yes")
                    {
                        rspMsg.Body = new BodyResponse()
                        {
                            MSGID    = reqMsg.Header.MSGID,
                            RESPONSE = CONSTANTS.DENIED
                        };

                        MessageUtil.Send(fileClient.stream, rspMsg);

                        ClientClose(fileClient);
                        ClientLock = false;
                        continue;
                    }
                    else
                    {
                        MessageUtil.Send(fileClient.stream, rspMsg);
                    }

                    WriteLine("파일 전송을 시작합니다.");

                    long   fileSize   = reqBody.FILESIZE;
                    string fileName   = Encoding.Default.GetString(reqBody.FILENAME);
                    string saveFolder = Encoding.Default.GetString(reqBody.FOLDERNAME);

                    string dir = Directory.GetCurrentDirectory() + "\\" + saveFolder;

                    if (Directory.Exists(dir) == false)
                    {
                        Directory.CreateDirectory(dir);
                    }

                    FileStream file = new FileStream(dir + "\\" + fileName, FileMode.Create);

                    uint?  dataMsgId = null;
                    ushort prevSeq   = 0;
                    while ((reqMsg = MessageUtil.Receive(fileClient.stream)) != null)
                    {
                        if (reqMsg.Header.MSGTYPE != CONSTANTS.FILE_SEND_DATA)
                        {
                            break;
                        }
                        if (dataMsgId == null)
                        {
                            dataMsgId = reqMsg.Header.MSGID;
                        }
                        else
                        {
                            if (dataMsgId != reqMsg.Header.MSGID)
                            {
                                break;
                            }
                        }
                        if (prevSeq++ != reqMsg.Header.SEQ)
                        {
                            WriteLine($"{prevSeq}, {reqMsg.Header.SEQ}");
                            break;
                        }

                        file.Write(reqMsg.Body.GetBytes(), 0, reqMsg.Body.GetSize());

                        if (reqMsg.Header.FRAGMENTED == CONSTANTS.NOT_FRAGMENTED)
                        {
                            break;
                        }
                        if (reqMsg.Header.LASTMSG == CONSTANTS.LASTMSG)
                        {
                            break;
                        }
                    }

                    long recvFileSize = file.Length;
                    file.Close();

                    WriteLine();
                    WriteLine($"수신 파일 크기 {recvFileSize} bytes");

                    Message rstMsg = new Message();
                    rstMsg.Body = new BodyResult()
                    {
                        MSGID  = reqMsg.Header.MSGID,
                        RESULT = CONSTANTS.SUCCESS
                    };
                    rstMsg.Header = new Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = CONSTANTS.FILE_SEND_RES,
                        BODYLEN    = (uint)rstMsg.Body.GetSize(),
                        FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                        LASTMSG    = CONSTANTS.LASTMSG,
                        SEQ        = 0
                    };
                    if (fileSize == recvFileSize)
                    {
                        MessageUtil.Send(fileClient.stream, rstMsg);
                    }
                    else
                    {
                        rstMsg.Body = new BodyResult()
                        {
                            MSGID  = reqMsg.Header.MSGID,
                            RESULT = CONSTANTS.FAIL
                        };
                        MessageUtil.Send(fileClient.stream, rstMsg);
                    }
                    WriteLine("파일 전송을 마쳤습니다.");
                }
            }
            catch (SocketException e)
            {
                WriteLine($"ErrorCode : {e.ErrorCode}");
                WriteLine(e);
            }
            finally
            {
                server.Stop();
            }
            WriteLine("서버를 종료합니다.");
        }
Exemple #15
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine($"사용법 : {Process.GetCurrentProcess().ProcessName} <Directory>");
                return;
            }

            uint msgID = 0;

            string dir = args[0];

            if (false == Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            const int   bindPort = 5425;
            TcpListener server   = null;

            try
            {
                IPEndPoint localAddress = new IPEndPoint(0, bindPort);

                server = new TcpListener(localAddress);
                server.Start();

                Console.WriteLine("파일 업로드 서버 시작...");
                while (true)
                {
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine($"클라이언트 접속 : {((IPEndPoint) client.Client.RemoteEndPoint).ToString()}");

                    NetworkStream stream = client.GetStream();

                    Message reqMsg = MessageUtil.Receive(stream);
                    if (reqMsg.Header.MSGTYPE != CONSTANTS.REQ_FILE_SEND)
                    {
                        stream.Close();
                        client.Close();
                        continue;
                    }

                    BodyRequest reqBody = reqMsg.Body as BodyRequest;
                    Console.WriteLine("파일 업로드 요청이 왔습니다. 수락하시겠습니까? yes or no");
                    string answer = Console.ReadLine();

                    Message repMsg = new Message();
                    {
                        if (answer != "yes")
                        {
                            repMsg.Body = new BodyResponse()
                            {
                                MSGID    = reqMsg.Header.MSGID,
                                RESPONSE = CONSTANTS.DENINED
                            };
                        }
                        else
                        {
                            repMsg.Body = new BodyResponse()
                            {
                                MSGID    = reqMsg.Header.MSGID,
                                RESPONSE = CONSTANTS.ACCEPTED
                            };
                        }

                        repMsg.Header = new Header()
                        {
                            MSGID      = msgID++,
                            MSGTYPE    = CONSTANTS.REP_FILE_SEND,
                            BODYLEN    = (uint)repMsg.Body.GetSize(),
                            FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                            LASTMSG    = CONSTANTS.NOT_LASMSG,
                            SEQ        = 0
                        };
                        MessageUtil.Send(stream, repMsg);
                    }
                    if (answer != "yes")
                    {
                        stream.Close();
                        client.Close();
                        continue;
                    }

                    Console.WriteLine("파일 전송을 시작합니다...");

                    long       fileSize = reqBody.FILESIZE;
                    string     fileName = Encoding.Default.GetString(reqBody.FILENAME);
                    FileStream file     = new FileStream($@"{dir}\{fileName}", FileMode.Create);

                    uint?  dataMsgID = null;
                    ushort prevSeq   = 0;
                    while (null != (reqMsg = MessageUtil.Receive(stream)))
                    {
                        Console.Write("#");
                        if (reqMsg.Header.MSGTYPE != CONSTANTS.FILE_SEND_DATA)
                        {
                            break;
                        }

                        if (null == dataMsgID)
                        {
                            dataMsgID = reqMsg.Header.MSGID;
                        }
                        else if (reqMsg.Header.MSGID != dataMsgID)
                        {
                            break;
                        }

                        if (reqMsg.Header.SEQ != prevSeq++)
                        {
                            Console.WriteLine($"{prevSeq}, {reqMsg.Header.SEQ}");
                            break;
                        }

                        file.Write(reqMsg.Body.GetBytes(), 0, reqMsg.Body.GetSize());

                        // 미분할 데이터 체크
                        if (CONSTANTS.NOT_FRAGMENTED == reqMsg.Header.FRAGMENTED)
                        {
                            break;
                        }

                        // 마지막 분할 데이터 체크
                        if (CONSTANTS.LASTMSG == reqMsg.Header.LASTMSG)
                        {
                            break;
                        }
                    }

                    long recvFileSize = file.Length;
                    file.Close();

                    Console.WriteLine();
                    Console.WriteLine($"수신 파일 크기 : {recvFileSize} bytes");

                    Message rstMsg = new Message();
                    {
                        if (recvFileSize == fileSize)
                        {
                            rstMsg.Body = new BodyResult()
                            {
                                MSGID  = reqMsg.Header.MSGID,
                                RESULT = CONSTANTS.SUCCESS
                            };
                        }
                        else
                        {
                            rstMsg.Body = new BodyResult()
                            {
                                MSGID  = reqMsg.Header.MSGID,
                                RESULT = CONSTANTS.FAIl
                            };
                        }

                        rstMsg.Header = new Header()
                        {
                            MSGID      = msgID++,
                            MSGTYPE    = CONSTANTS.FILE_SEND_RES,
                            BODYLEN    = (uint)rstMsg.Body.GetSize(),
                            FRAGMENTED = CONSTANTS.NOT_FRAGMENTED,
                            LASTMSG    = CONSTANTS.LASTMSG,
                            SEQ        = 0
                        };
                        MessageUtil.Send(stream, rstMsg);
                    }

                    Console.WriteLine("파일 전송을 마쳤습니다.");
                    stream.Close();
                    client.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                server.Stop();
            }

            Console.WriteLine("서버를 종료합니다.");
            Console.ReadLine();
        }
Exemple #16
0
 public ReportRequest()
 {
     this.Header = new HeaderRequest();
     this.Body   = null;
 }