// 파일에서 한줄 읽어온다.
        public string readLine()
        {
            string res = file.ReadLine();

#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("ReadLine : {0} ", res);
#endif
            return(res);
        }
示例#2
0
        private static void Send_Server(Socket handler, String data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("[Server] send data:[{0}] to client", data);
#endif
            // Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0,
                              new AsyncCallback(SendCallback_Server), handler);
        }
示例#3
0
        /// <summary>
        /// recv packet 부분이 분리되서 처리
        /// </summary>
        public static void StartAsyncClient()
        {
            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // The name of the

                /*
                 *              // remote device is "host.contoso.com".
                 *              IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");// ("host.contoso.com");
                 *              IPAddress ipAddress = ipHostInfo.AddressList[0];
                 */
                //현재 PC의 IP로 대체

                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                //IPAddress ipAddress = ipHostInfo.AddressList[0];  // ipv6
                IPAddress ipAddress = ipHostInfo.AddressList[1]; // ipv4

                IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

                // Create a TCP/IP socket.
                Socket client = new Socket(ipAddress.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                // Connect to the remote endpoint.
                client.BeginConnect(remoteEP,
                                    new AsyncCallback(ConnectCallback_client_async), client);
                connectDone_client_async.WaitOne();

                // Send test data to the remote device.
                Send_client_async(client, "This is a test<EOF>");
                sendDone_client_async.WaitOne();

                // Receive the response from the remote device.
                Receive_client_async(client);
                receiveDone_client_async.WaitOne();

                // Write the response to the console.
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("Response received : {0}", response);
#endif

                // Release the socket.
                client.Shutdown(SocketShutdown.Both);
                client.Close();
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
        }
示例#4
0
     public static void StartServerWithThread()
     {
         // TCP 소켓 server/client sample //
         //MyClass_Networks.StartListeningAsync();
         // bool threadStop = false;
         /// var
         server_t = new System.Threading.Thread(() => serverThreaRun()); // 서버는 별도 thread에서 실행
         server_t.Start();                                               // 시작
 #if DEBUG_PRINT_ENABLE
         MyClass_Dprint.debugPrint("start StartClientSync");
 #endif
     }
示例#5
0
        public static void StartServerListeningAsync()
        {
            // Data buffer for incoming data.
            byte[] bytes = new Byte[1024];
            // Establish the local endpoint for the socket.
            // The DNS name of the computer
            // running the listener is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            //IPAddress ipAddress = ipHostInfo.AddressList[0];  // ipv6
            IPAddress  ipAddress     = ipHostInfo.AddressList[1]; // ipv4
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Socket listener = new Socket(ipAddress.AddressFamily,
                                         SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);

                while (true)
                {
                    // Set the event to nonsignaled state.
                    allDone_server.Reset();

                    // Start an asynchronous socket to listen for connections.
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("[Server] Waiting for a connection...");
#endif
                    listener.BeginAccept(
                        new AsyncCallback(AcceptCallback_server),
                        listener);

                    // Wait until a connection is made before continuing.
                    allDone_server.WaitOne();
                }
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
#if DEBUG_PRINT_ENABLE
            //MyClass_Dprint.debugPrint("\nPress ENTER to continue...");
            MyClass_Dprint.debugPrint("[Server]  \nEnd server...");
#endif
            //			Console.Read();
        }
示例#6
0
        /// <summary>
        /// 클라이언트로 부터 recv 처리 callback
        /// </summary>
        /// <param name="ar"></param>
        public static void ReadCallback_server(IAsyncResult ar) // reveive file
        {
            String content = String.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workSocket;

            // Read data from the client socket.
            int bytesRead = handler.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There  might be more data, so store the data received so far.
                // connection이 남아있으면 EOF까지 계속 append되지만, connection close시에 reset됨.
                state.sb.Append(Encoding.ASCII.GetString(
                                    state.buffer, 0, bytesRead));

                // Check for end-of-file tag. If it is not there, read
                // more data.
                content = state.sb.ToString();
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("[server] Receved: {0}", content);
#endif
                if (content.IndexOf("<EOF>") > -1) // stream end DETECT ***
                //if(content.IndexOf("\r\n") > -1 || content.IndexOf("\n") > -1  || content.IndexOf("\r") > -1)
                {
                    // All the data has been read from the
                    // client. Display it on the console.
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("[Server] Read {0} bytes from socket. \n Data : {1}", content.Length, content);
#endif
                    if (content.Contains("test")) // check 샘플
                    {
#if DEBUG_PRINT_ENABLE
                        MyClass_Dprint.debugPrint("[Server] test command received! ");
#endif
                    }
                    // 받은 메세지를 다시 client로 보낸다.
                    Send_Server(handler, content);
                }
                else // 연속된 data를 받아서 append하는 case.
                {
                    // Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                         new AsyncCallback(ReadCallback_server), state);
                }
            }
        }
示例#7
0
        public void MyClass_Parse_And_Report4(string inputLog, string outputTxt)
        {
            // log 포맷 시간(19)#타입(2)#메시지코드(9)
            // 입력받은 text log 파일을 열어, #으로 split 한 후 각 type 별로 분리하고 카운팅한 결과를 output text에 저장
            MyClass_Files_Reader srcFile  = new MyClass_Files_Reader(inputLog);
            MyClass_Strings      strClass = new MyClass_Strings();
            string res = srcFile.readLine();             // 1 line read

            string[] line = srcFile.readLines(inputLog); // read all lines
            int      num  = line.Count();                // total count

#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("read lines:" + num);
#endif
            int            typeCount = strClass.countingAllTypes(line, delimiter, 1);
            string[]       logTypes  = strClass.getAllTypes(line, delimiter, 1);
            MyClass_Thread myThread  = new MyClass_Thread();
            // Example #4: Append new text to an existing file.
            // The using statement automatically flushes AND CLOSES the stream and calls
            // IDisposable.Dispose on the stream object.
            using (System.IO.StreamWriter outFile = new System.IO.StreamWriter(outputTxt, false))
            {
                foreach (string s in logTypes)
                {
                    //string[] data = strClass.StringSplit(s, delimiter);
                    int cnt = strClass.getCountOfType(line, delimiter, 1, s);
                    // 타입별 출력 파일 생성
                    MyClass_Files_Writer fileWriter = new MyClass_Files_Writer("TYPELOG_4_" + s + ".TXT");
                    // file writer 클래스에 thread safty하도록 lock 추가. (여러 thread에서 동시에 write의 경우 처리)


                    string[] strResult = strClass.getLinesOfType(line, delimiter, 1, s);// 입력된 타입에 해당되는 로그 만 추출한다.
                    foreach (string _line in strResult)
                    {
                        // 이부분 multi thread로 바꾼다.
#if DEBUG_PRINT_ENABLE
                        MyClass_Dprint.debugPrint("type: " + s);
                        MyClass_Dprint.debugPrint("line: " + _line);
#endif
                        myThread.StartConvertAndWrite(fileWriter, _line, delimiter, 2);
                    }
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("type:" + s + " total num:" + cnt);
#endif
                    outFile.WriteLine(s + "#" + cnt);
                }
            }
        }
示例#8
0
        public void MyClass_Parse_And_Report3(string inputLog, string outputTxt)
        {
            // log 포맷 시간(19)#타입(2)#메시지코드(9)
            // 입력받은 text log 파일을 열어, #으로 split 한 후 각 type 별로 분리하고 카운팅한 결과를 output text에 저장
            MyClass_Files_Reader srcFile  = new MyClass_Files_Reader(inputLog);
            MyClass_Strings      strClass = new MyClass_Strings();
            string res = srcFile.readLine();             // 1 line read

            string[] line = srcFile.readLines(inputLog); // read all lines
            int      num  = line.Count();                // total count

#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("read lines:" + num);
#endif
            int            typeCount = strClass.countingAllTypes(line, delimiter, 1);
            string[]       logTypes  = strClass.getAllTypes(line, delimiter, 1);
            MyClass_Thread myThread  = new MyClass_Thread();
            // Example #4: Append new text to an existing file.
            // The using statement automatically flushes AND CLOSES the stream and calls
            // IDisposable.Dispose on the stream object.
            using (System.IO.StreamWriter outFile =
                       new System.IO.StreamWriter(outputTxt, false))
            {
                foreach (string s in logTypes)
                {
                    //string[] data = strClass.StringSplit(s, delimiter);
                    int cnt = strClass.getCountOfType(line, delimiter, 1, s);

                    string[] strResult = strClass.getLinesOfType(line, delimiter, 1, s);// 타입별 로그를 추출한다.
                    foreach (string _line in strResult)
                    {
                        // convert and write to file
                        using (System.IO.StreamWriter file = new System.IO.StreamWriter("TYPELOG_3_" + s + ".TXT", false))
                        {
                            string convertedStr = strClass.convertStringMsg(_line, delimiter, 2);
                            {
                                file.WriteLine(convertedStr);
                            }
                        }
                    }
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("type:" + s + " total num:" + cnt);
#endif
                    outFile.WriteLine(s + "#" + cnt);
                }
            }
        }
示例#9
0
        private static void StringCombination(string s, StringBuilder sb, int index)
        {
            for (int i = index; i < s.Length; i++)
            {
                // 1) 한 문자 추가
                sb.Append(s[i]);

                // 2) 구한 문자조합 출력
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(sb.ToString());
#endif
                // 3) 나머지 문자들에 대한 조합 구하기
                StringCombination(s, sb, i + 1);

                // 위의 1에서 추가한 문자 삭제
                sb.Remove(sb.Length - 1, 1);
            }
        }
示例#10
0
        public void Test()
        {
            int[] coins = { 1, 10, 50, 100 };

            // CoinChangeCount c = new CoinChangeCount();
            // 1.  Recursive 방식 해결
            int ans = this.Count(coins, 4, 90);

#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("Count={0}", ans);
#endif
            // 2. 중간 결과를 저장(Memoization)하여 Lookup하는 방식 해결
            Dictionary <Tuple <int, int>, int> hash = new Dictionary <Tuple <int, int>, int>();
            ans = this.DPCount(coins, 4, 90, hash);
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("DPCount={0}", ans);
#endif
        }
示例#11
0
        // 폴더 내 전체 파일 스캔
        public static void TreeScan(string sDir)
        {
            foreach (string f in System.IO.Directory.GetFiles(sDir))
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("File: " + f); // or some other file processing
                                                         // 파일 name 출력
#endif
            }

            foreach (string d in System.IO.Directory.GetDirectories(sDir))
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("dir: " + d); // 디렉토리 name 출력
#endif
                TreeScan(d);                            // recursive call to get files of directory
            }
        }
示例#12
0
        /// <summary>
        /// 한줄 기록을 위한 WriteEntry 구현
        /// </summary>
        /// <param name="entry"></param>
        public void WriteEntry(string entry)
        {
            try
            {
                mutex.WaitOne();

                output.WriteLine("[" + DateTime.Now.ToString() + "]" + entry); // 로그 포맷~
                output.Flush();

                mutex.ReleaseMutex();
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.Message);
#endif
            }
        }
示例#13
0
        private static void Receive_client_async(Socket client)
        {
            try
            {
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = client;

                // Begin receiving the data from the remote device.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                    new AsyncCallback(ReceiveCallback_client_async), state);
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
        }
示例#14
0
        public int Count(int[] coins, int m, int n)
        {
            if (n == 0)
            {
                return(1);
            }
            if (n < 0)
            {
                return(0);
            }
            if (m <= 0)
            {
                return(0);
            }
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("m:{0}, n:{1}", m, n);
#endif
            return(Count(coins, m - 1, n) + Count(coins, m, n - coins[m - 1]));
        }
示例#15
0
        /// <summary>
        /// 파일 전체를 읽어서 new line 타입을 최초에 detect 되는 타입으로 판단/return 한다.
        /// 2종류가 혼재되어 있지 않은 것을 전제한다.
        public string getNewLine()
        {
            //string[] readStr = this.readLines(mFilePath);
            string res = this.readAllText(mFilePath);

            if (res.Contains("\r\n"))
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(" new line with carriage return.");
#endif
                return("\r\n"); // 캐리지 리턴이 포함됨.
            }
            else if (res.Contains("\n"))
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(" new line");
#endif
                return("\n");
            }
            return(string.Empty);
        }
示例#16
0
        /// <summary>
        /// 지정된 폴더 내의 지정된 형식(filePrefix_x.x.x) 지정한 확장자의 파일 들을 스캔
        /// </summary>
        public static string[] scanFolderAndUpdate_Filelists(string targetPath, string extension)
        {
            List <string> strings = new List <string>();

            if (!System.IO.Directory.Exists(targetPath)) // 없으면
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("error. tar folder not found. ");
#endif
                return(strings.ToArray());
            }
            string[] filePaths = System.IO.Directory.GetFiles(targetPath + "\\", "*." + extension);
            int      lengthA   = filePaths.Length;
            // 내림차순 정렬...
            var desc = from s in filePaths
                       orderby s descending
                       select s;
            foreach (string s in desc)
            {
                // get file name only
                string fileName = System.IO.Path.GetFileNameWithoutExtension(s);
                // 파일 이름에서 특정 패턴 매칭하여 버전등의 정보만 추출
                System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(fileName, @"filePrefix_([A-Za-z0-9\-\.]+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    // Finally, we get the Group value and display item
                    string key = match.Groups[1].Value;
                    // add to string list.
                    strings.Add(key);
                }
            }
            if (strings.Count <= 0)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("[scanFolder] error. no file in dir. ");
#endif
                return(strings.ToArray());
            }
            return(strings.ToArray());
        }
示例#17
0
        private static void SendCallback_Server(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("Sent {0} bytes to client.", bytesSent);
#endif
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("[Server] {0}", e.ToString());
#endif
            }
        }
示例#18
0
        private static void ReceiveCallback_client_async(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                StateObject state  = (StateObject)ar.AsyncState;
                Socket      client = state.workSocket;

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    // Get the rest of the data.
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                        new AsyncCallback(ReceiveCallback_client_async), state);
                }
                else
                {
                    // All the data has arrived; put it in response.
                    if (state.sb.Length > 1)
                    {
                        response = state.sb.ToString();
                    }
                    // Signal that all bytes have been received.
                    receiveDone_client_async.Set();
                }
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
        }
示例#19
0
        /// <summary>
        /// 목록 전체 기록을 위한 WriteEntry 구현
        /// </summary>
        /// <param name="entry"></param>
        public void WriteEntry(System.Collections.ArrayList entry)
        {
            try
            {
                mutex.WaitOne();

                System.Collections.IEnumerator line = entry.GetEnumerator();
                while (line.MoveNext())
                {
                    output.WriteLine(line.Current);
                }
                output.WriteLine();
                output.Flush();

                mutex.ReleaseMutex();
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.Message);
#endif
            }
        }
示例#20
0
        private static void ConnectCallback_client_async(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete the connection.
                client.EndConnect(ar);
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("Socket connected to {0}",
                                          client.RemoteEndPoint.ToString());
#endif
                // Signal that the connection has been made.
                connectDone_client_async.Set();
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
        }
示例#21
0
        private static void SendCallback_client_async(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = client.EndSend(ar);
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("Sent {0} bytes to server.", bytesSent);
#endif

                // Signal that all bytes have been sent.
                sendDone_client_async.Set();
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
        }
示例#22
0
        public void MyClass_Parse_And_Report2(string inputLog, string outputTxt)
        {
            // log 포맷 시간(19)#타입(2)#메시지코드(9)
            // 입력받은 text log 파일을 열어, #으로 split 한 후 각 type 별로 분리하고 카운팅한 결과를 output text에 저장
            MyClass_Files_Reader srcFile  = new MyClass_Files_Reader(inputLog);
            MyClass_Strings      strClass = new MyClass_Strings();
            string res = srcFile.readLine();             // 1 line read

            string[] line = srcFile.readLines(inputLog); // read all lines
            int      num  = line.Count();                // total count

#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("read lines:" + num);
#endif
            int      typeCount = strClass.countingAllTypes(line, delimiter, 1);
            string[] logTypes  = strClass.getAllTypes(line, delimiter, 1);

            // Example #4: Append new text to an existing file.
            // The using statement automatically flushes AND CLOSES the stream and calls
            // IDisposable.Dispose on the stream object.
            using (System.IO.StreamWriter outFile =
                       new System.IO.StreamWriter(outputTxt, true))
            {
                //outFile.WriteLine("Fourth line");
                // scan types
                foreach (string s in logTypes)
                {
                    //string[] data = strClass.StringSplit(s, delimiter);
                    int cnt = strClass.getCountOfType(line, delimiter, 1, s);
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("type:" + s + " total num:" + cnt);
#endif
                    outFile.WriteLine(s + "#" + cnt);
                }
            }
        }
示例#23
0
        /// <summary>
        /// FileLogger 생성자, Application 실행 디렉토리/log 에 파일을 생성
        /// </summary>
        /// <param name="name">file path</param>
        public MyClass_Logger(string name)
        {
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
            MyClass_Dprint.debugPrint(System.AppDomain.CurrentDomain.BaseDirectory);
            MyClass_Dprint.debugPrint(System.Environment.CurrentDirectory);
            MyClass_Dprint.debugPrint(System.IO.Directory.GetCurrentDirectory());
            MyClass_Dprint.debugPrint(Environment.CurrentDirectory);
#endif
            //To get the location the assembly normally resides on disk or the install directory
            string _path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
            //once you have the path you get the directory with:
            var directory = System.IO.Path.GetDirectoryName(_path);
            // string absPath = new Uri(directory).AbsolutePath;
            directory = directory.Replace(@"file:\", "");
            string path     = directory + "\\log\\";
            string fullname = path + name;

            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            output = new System.IO.StreamWriter(fullname, true);
        }
示例#24
0
        public static string StartClientSync(string data, bool recvReply)
        {
            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];
            string res   = string.Empty;

            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // This example uses port 2012 on the local computer.
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                //IPAddress ipAddress = ipHostInfo.AddressList[0];  // ipv6
                IPAddress  ipAddress = ipHostInfo.AddressList[1]; // ipv4
                IPEndPoint remoteEP  = new IPEndPoint(ipAddress, port);

                // Create a TCP/IP  socket.
                Socket sender = new Socket(ipAddress.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    sender.Connect(remoteEP);
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("[Client] Socket connected to {0}", sender.RemoteEndPoint.ToString());
                    MyClass_Dprint.debugPrint("[Client] Send data [{0}] to server", data);
#endif
                    // Encode the data string into a byte array.
                    byte[] msg = Encoding.ASCII.GetBytes(data);

                    // Send the data through the socket.
                    int bytesSent = sender.Send(msg);
                    //bytesSent = sender.Send(msg);
                    if (recvReply == true) // 서버로 부터 reply 받는 경우
                    {
#if DEBUG_PRINT_ENABLE
                        // Receive the response from the remote device.
                        MyClass_Dprint.debugPrint("[Client] wait reply...");
#endif
                        int bytesRec = sender.Receive(bytes);
#if DEBUG_PRINT_ENABLE
                        MyClass_Dprint.debugPrint("[Client] Echoed data : {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
#endif
                        res = Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    }
                    // Release the socket.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                catch (ArgumentNullException ane)
                {
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("[Client] ArgumentNullException : {0}", ane.ToString());
#endif
                }
                catch (SocketException se)
                {
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("[Client] SocketException : {0}", se.ToString());
#endif
                }
                catch (Exception e)
                {
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("[Client] Unexpected exception : {0}", e.ToString());
#endif
                }
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint("[Client] {0}", e.ToString());
#endif
            }
            return(res);
        }
示例#25
0
        public void run_Test()
        {
#if false
            // 도서관리 sample
            MyClass_BookManager bm = new MyClass_BookManager();
            bm.Run();
#endif
#if false
            // 100의 bitcoins 전송 sample //
            List <MyClassBlockChain> blockchain = new List <MyClassBlockChain>();
            // Genesis block
            string[] transactions = { "Jone Sent 100 Bitcoins to Bob." };
            // 최초 노드 : genesisBlock
            myClassBlockChainHeader blockheader  = new myClassBlockChainHeader(null, transactions);
            MyClassBlockChain       genesisBlock = new MyClassBlockChain(blockheader, transactions);
            Console.WriteLine("Block Hash : {0}", genesisBlock.getBlockHash());

            Stopwatch         stopw         = new Stopwatch();//시간 측정 클래스
            MyClassBlockChain previousBlock = genesisBlock;
            for (int i = 0; i < 5; i++)
            {
                myClassBlockChainHeader secondBlockheader = new myClassBlockChainHeader(Encoding.UTF8.GetBytes(previousBlock.getBlockHash()), transactions);
                MyClassBlockChain       nextBlock         = new MyClassBlockChain(secondBlockheader, transactions);
                stopw.Start();
                int count = secondBlockheader.ProofOfWorkCount();
                stopw.Stop();
                Console.WriteLine("{0} th Block Hash : {1}", i.ToString(), nextBlock.getBlockHash());
                Console.WriteLine("   └ COUNT of Proof of Work : {0} th loop", count);
                Console.WriteLine("   └ Delay : {0} millisecond", stopw.ElapsedMilliseconds);
                previousBlock = nextBlock;
                stopw.Reset();
            }
#endif

            // Array to List
            int[]      ints = new[] { 10, 20, 10, 34, 113 };
            List <int> lst  = ints.OfType <int>().ToList();
            lst.AddRange(new int[] { 10, 20, 10, 34, 113 });
            // List to Array
            int [] intsArray = lst.ToArray();

            //중복되지 않는 첫번째 문자 구하기 // dictionary 사용
            string s  = "abcabdefe";
            char   ch = MyClass_Strings.GetFirstChar(s.ToCharArray());
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint(ch);
#endif

            // 문자열 내 문자로 가능한 조합 구하기
            MyClass_Strings.getStringCombination("ABC");

            // string 내 패턴 스트링 카운팅
            string sampleData = "asdfkk;lkasldfajsdlkfj999kajsdlfkjasdlfkj9999kljflaskdflkajsdlfkjasdlkfj999lkajsdlfkjasldfkja999";
            // 정규식 매칭 확인 + count
            //int countResult = System.Text.RegularExpressions.Regex.Matches(sampleData, "999").Count;
            int   countResult = MyClass_Strings.countMatches(sampleData, "999");
            Match matchRes    = Regex.Match(sampleData, "999");
            // recursive하게 sub folder에서 유일한 file 찾기 예
            string fullPath = MyClass_Files.findFileFromSubFolder(".", "test.txt");

            // 스트링내 캐릭터 조합 비교 예
            string res  = string.Empty;
            int    ress = MyClass_Strings.checkCharsInString("coffee", "fofeefac", ref res);

            // 라인브레이크 사용자설정 예  // append mode on/off 예
            MyClass_Files_Writer fileWriter = new MyClass_Files_Writer("fileWrite.TXT", false);
            fileWriter.customNewLine = "\r\n";
            fileWriter.WriteToFile("asdfasdfasdfasdf");
            fileWriter.WriteToFile("asdfasdfasdfasdf");
            fileWriter.WriteToFile("asdfasdfasdfasdf");
            // 소스의 라인브레이크 디텍션 예
            MyClass_Files_Reader reader = new MyClass_Files_Reader("fileWrite.TXT");
            string getNewLineChar       = reader.getNewLine(); // newLine 형식 읽어와서 file writer의 customNewLine에도 맞춰주면 된다.

            // 암호화 예
            string str_test  = "3#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string str_Enc   = MyClass_Security.CaesarCipherEncrypt(str_test, 20);
            string str_test2 = "21#abcdefghijklmnopqrstuvwxyz";
            string str_Enc2  = MyClass_Security.CaesarCipherEncrypt(str_test2, 20);

            //


            // 메서드로 바꿀것
            // ABC 부품을 갖고 A7 B7 C7이 순서대로 오면 제품 조립 ok
            // 총 완성 제품 counting
            string str_Product_struct   = "A2B3A7B7C7B2C7A9B4A9B8C7A2B7C9";
            char[] array_Product_struct = str_Product_struct.ToCharArray();
            int    status            = 0; //1:A ok, 2:B ok, 3:C ok
            int    totalProductCount = 0;
            for (int i = 0; i < array_Product_struct.Length; i = i + 2)
            {
                string num = string.Empty;
                num += array_Product_struct[i + 1];
                int part_count = Convert.ToInt32(num);
                //int level2 = Convert.ToInt32("-1024");
                //int level = (int)Char.GetNumericValue(array_Product_struct[i + 1]);//Convert.ToInt32(array_Product_struct[i + 1]);
                if (array_Product_struct[i] == 'A')
                {
                    if (part_count >= 7)
                    {
                        status = 1;
                    }
                    else
                    {
                        status = 0;
                    }
                }
                if (array_Product_struct[i] == 'B' && status == 1)
                {
                    if (part_count >= 7)
                    {
                        status = 2;
                    }
                    else
                    {
                        status = 0;
                    }
                }
                if (array_Product_struct[i] == 'C' && status == 2)
                {
                    if (part_count >= 7)
                    {
                        //status = 3;
                        // count up
                        status = 0;
                        totalProductCount++;
                    }
                    else
                    {
                        status = 0;
                    }
                }
            }
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("totalProductCount: " + totalProductCount);
#endif

            // 구조체 타입 list의 정렬 예
            //MyClass_list_sort<int> lSortTest = new MyClass_list_sort<int>();
            MyClass_list_sort.test();
            //MyClass_array_sort sortTest = new MyClass_array_sort();
            MyClass_array_sort.test();

            // 헤시맵을 이용한 정렬 TODO
            MyClass_hashMap hashTest = new MyClass_hashMap();  // TODO...
            hashTest.test();

            // 링크드리스트 사용 예
            //MyClass_linkedList list = new MyClass_linkedList();
            MyClass_linkedList.test();

            // 동전바꿈 예
            MyClass_coinChangeCount cnt = new MyClass_coinChangeCount();
            cnt.Test();


            // MyClass_Parse_Log parse = new MyClass_Parse_Log('#'); // delimitor
            // 문제 sample //
            // parse.MyClass_Parse_And_Report1("LOGFILE_A.TXT", "REPORT_1.TXT");            // 문제 2
            //parse.MyClass_Parse_And_Report2("LOGFILE_B.TXT", "REPORT_2.TXT");
            //parse.MyClass_Parse_And_Report3("LOGFILE_B.TXT", "REPORT_3.TXT");
            //parse.MyClass_Parse_And_Report4("LOGFILE_B.TXT", "REPORT_4.TXT");


            // 암호/복호화 sample //
            String originalText = "plain text";
            String key          = "key";
            String en           = MyClass_Security.Encrypt(originalText, key);
            String de           = MyClass_Security.Decrypt(en, key);
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("Original Text is " + originalText);
            MyClass_Dprint.debugPrint("Encrypted Text is " + en);
            MyClass_Dprint.debugPrint("Decrypted Text is " + de);
#endif
            MyClass_Networks.StartServerWithThread();
            //string testSend = MyClass_Networks.StartClientSync("1111111");
            string testSend2 = MyClass_Networks.StartClientSync("send data 111111 ", false);
            //testSend2 = MyClass_Networks.StartClientSync("222222 ", false);
            testSend2 = MyClass_Networks.StartClientSync("test <EOF>", true);
#if DEBUG_PRINT_ENABLE
            // MyClass_Dprint.debugPrint("start StartAsyncClient");
#endif
            //MyClass_Networks.StartAsyncClient("test <EOF>");
            //MyClass_Networks.StartAsyncClient("<EOF>");
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("abort socket server thread");
#endif

            MyClass_Networks.StopServerWithThread();

            // 폴더 스캔 샘플 //
            MyClass_Files.TreeScan(".\\..");
            // 지정한 확장자를 가진 파일을 폴더내에서 찾아 list로 update
            string[] resultt = MyClass_Files.scanFolderAndUpdate_Filelists(".", "cs");

            // 로그파일 쓰기 예 //
            MyClass_Logger log = new MyClass_Logger("restLog.txt");
            log.WriteEntry("TTTTTTTTTTTTTTTTTTTTTTTTT");

            // 링버퍼 샘플 //
            MyClass_RandomData rndData = new MyClass_RandomData();
            rndData.rnd = new Random();                          // random 초기화..
            var data = rndData.GenerateRandomData(10);           // 100개의 random 데이터 생성
            // MyClass_CircularBuffer<타입>(갯수)
            var buffer = new MyClass_CircularBuffer <byte>(100); // 링버퍼 생성
            buffer.Put(data);                                    // 10 byte push
            data = rndData.GenerateRandomData(10);
            buffer.Put(data);
            //TestTools.UnitTesting.CollectionAssert.AreEqual(data, buffer.ToArray());
            var ret = new byte[10]; //[buffer.Size];
            buffer.Get(ret);
            buffer.Get(ret);        // buffer size만큼 get

            //CollectionAssert.AreEqual(data, ret);
            //Assert.IsTrue(buffer.Size == 0);

            int test = 2;
        }
示例#26
0
        /*
         * //create comparer
         * internal class PersonComparer : IComparer<Gameharacter>
         * {
         *  public int Compare(Gameharacter x, Gameharacter y)
         *  {
         *      //first by age
         *      int result = x._CharCd.CompareTo(y._CharCd);
         *
         *      //then name
         *      if (result == 0)
         *          result = x._Level.CompareTo(y._Level);
         *
         *      //a third sort
         *      if (result == 0)
         *          result = x._Money.CompareTo(y._Money);
         *
         *      return result;
         *  }
         * }
         */
        public void test()
        {
            Hashtable ht = new Hashtable();

            ht.Add("irina", "Irina SP");
            ht.Add("tom", "Tom Cr");

            if (ht.Contains("tom"))
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(ht["tom"]);
#endif
            }
            ///////////////////////////////

            Hashtable    htt        = new Hashtable();                    // 해시 테이블 생성
            Gameharacter Character1 = new Gameharacter(12, 7, 1000);      // 구조체1
            htt.Add(12, Character1);                                      // 추가
            Gameharacter Character2 = new Gameharacter(5, 200, 111000);   // 구조체  2
            htt.Add(15, Character2);                                      // 추가
            Gameharacter Character3 = new Gameharacter(200, 34, 3345000); // 구조체 3
            htt.Add(200, Character3);                                     // 추가
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("before");
#endif
            foreach (DictionaryEntry entry in htt) // 상태 출력
            {
                Gameharacter getStr = (Gameharacter)entry.Value;
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(entry.Key + ":" + getStr._CharCd);
#endif
            }
            htt.Remove(200); // key 200 제거
#if DEBUG_PRINT_ENABLE
            MyClass_Dprint.debugPrint("after");
#endif
            foreach (DictionaryEntry entry in htt) // 상태 출력
            {
                Gameharacter getStr = (Gameharacter)entry.Value;
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(entry.Key + ":" + getStr._CharCd);
#endif
            }
            // IDictionary<string, Gameharacter> d = htt; // your hash table
            //var ordered = d.OrderBy(p => p.Key).ToList();
            // foreach (var p in ordered)
            // {
#if DEBUG_PRINT_ENABLE
            //    MyClass_Dprint.debugPrint("Key: {0} Value: {1}", p.Key, p.Value);
#endif
            //  }
            SortedList sorter2 = new SortedList(htt);
            foreach (DictionaryEntry entry in htt) // 상태 출력
            {
                Gameharacter getStr = (Gameharacter)entry.Value;
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(entry.Key + ":" + getStr._CharCd + "|" + getStr._Level + ":" + getStr._Money);
#endif
            }


            int test = 0;
        }
示例#27
0
        // 동기 클라이언트 소켓
        public static void StartClientSync()
        {
            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];

            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // This example uses port 2012 on the local computer.
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                //IPAddress ipAddress = ipHostInfo.AddressList[0];  // ipv6
                IPAddress  ipAddress = ipHostInfo.AddressList[1]; // ipv4
                IPEndPoint remoteEP  = new IPEndPoint(ipAddress, port);
                // Create a TCP/IP  socket.
                Socket sender = new Socket(ipAddress.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);
                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    sender.Connect(remoteEP);
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("Socket connected to {0}", sender.RemoteEndPoint.ToString());
#endif
                    // Encode the data string into a byte array.
                    byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
                    // Send the data through the socket.
                    int bytesSent = sender.Send(msg);
                    // Receive the response from the remote device.
                    int bytesRec = sender.Receive(bytes);
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
#endif
                    // Release the socket.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                catch (ArgumentNullException ane)
                {
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("ArgumentNullException : {0}", ane.ToString());
#endif
                }
                catch (SocketException se)
                {
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("SocketException : {0}", se.ToString());
#endif
                }
                catch (Exception e)
                {
#if DEBUG_PRINT_ENABLE
                    MyClass_Dprint.debugPrint("Unexpected exception : {0}", e.ToString());
#endif
                }
            }
            catch (Exception e)
            {
#if DEBUG_PRINT_ENABLE
                MyClass_Dprint.debugPrint(e.ToString());
#endif
            }
        }