프로그래밍/C#

C# Socket Client Example

bluecandyg 2021. 3. 17. 11:15
                using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    // 서버 연결
                    var ip_endpoint = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.xxx"), xxxxx);
                    socket.Connect(ip_endpoint);

                    // 저장 Buffer
                    byte[] receiverBuffer = new byte[8192];

                    string test_key = string.Format("{0}00000", DateTime.Now.ToString("yyyyMMddHHmmss"));

                    while (bWorkCancel is false)
                    {
                        byte[] buffer = Encoding.GetEncoding("EUC-KR").GetBytes(test_key);

                        // 서버에 데이터 전송
                        socket.Send(buffer, SocketFlags.None);

                        // 서버에서 데이터 수신
                        int length = socket.Receive(receiverBuffer);

                        string data = Encoding.GetEncoding("EUC-KR").GetString(receiverBuffer, 0, length);

                        // parsing
                        string[] split_data = Regex.Split(data, @"\r\n", RegexOptions.IgnoreCase);
                        test_key = split_data[1];

                        // 1건만 테스트
                        break;
                    }


                    socket.Close();
                }