Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 7개 있습니다.)
.NET Framework: 248. 닷넷에서 지원되는 문자열 인코딩 이름 목록
; https://www.sysnet.pe.kr/2/0/1147

.NET Framework: 368. Encoding 타입의 대체(fallback) 메카니즘
; https://www.sysnet.pe.kr/2/0/1446

.NET Framework: 373. C# 문자열의 인코딩이란?
; https://www.sysnet.pe.kr/2/0/1461

.NET Framework: 701. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법
; https://www.sysnet.pe.kr/2/0/11378

.NET Framework: 702. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법(두 번째 이야기)
; https://www.sysnet.pe.kr/2/0/11381

.NET Framework: 867. C# - Encoding.Default 값을 바꿀 수 있을까요?
; https://www.sysnet.pe.kr/2/0/12037

닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
; https://www.sysnet.pe.kr/2/0/13506




한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법(두 번째 이야기)

지난 글에서 Decoder 타입의 사용법을 알아봤는데요.

한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법
; https://www.sysnet.pe.kr/2/0/11378

그런데, 실제 통신 환경에서 Decoder 타입을 유지하는 것은 왠지 오버헤드 같습니다. 그보다, 한글 조합이 안 된 상태의 바이트 배열을 다음번 조합으로 미루는 방법을 사용하는 것도 괜찮을 것 같습니다.

Decoder 타입을 보면, GetChars 메서드의 호출로 미완성의 char가 있는 경우 내부의 HasState 속성 값이 true로 바뀌면서 bits 필드로 상태 값을 유지하는데 모두 internal 접근자를 갖고 있습니다. 따라서 Reflection을 이용해 다음과 같이 처리하는 것도 가능합니다.

static void Test()
{
    int bits = 0;

    {
        Decoder utf8Decoder = Encoding.UTF8.GetDecoder();
        SendBuffer(utf8Decoder, buf1);
        bits = GetBits(utf8Decoder);
    }

    {
        Decoder utf8Decoder = Encoding.UTF8.GetDecoder();
        SetBits(utf8Decoder, bits);

        SendBuffer(utf8Decoder, buf2);
    }
}

private static void SetBits(Decoder utf8Decoder, int bits)
{
    FieldInfo fi = GetFieldInfo(utf8Decoder);
    fi.SetValue(utf8Decoder, bits);
}

private static FieldInfo GetFieldInfo(Decoder decoder)
{
    return decoder.GetType().GetField("bits", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
}

private static int GetBits(Decoder utf8Decoder)
{
    FieldInfo fi = GetFieldInfo(utf8Decoder);
    return (int)fi.GetValue(utf8Decoder);
}

보는 바와 같이 decoder 인스턴스를 유지하지 않아도 bits 값을 보존하는 것만으로 디코딩을 정상적으로 수행할 수 있습니다.




그런데, 왠지 public 접근자가 아닌 것이 좀 걸립니다. 그런 경우라면 그냥 Decoder 인스턴스를 직렬화해서 통신 간에 들고 있으면 됩니다.

byte[] buf = null;
{
    Decoder utf8Decoder = Encoding.UTF8.GetDecoder();
    SendBuffer(utf8Decoder, buf1);

    MemoryStream ms = new MemoryStream();
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(ms, utf8Decoder);

    buf = ms.ToArray();
}

{
    BinaryFormatter formatter = new BinaryFormatter();
    Decoder utf8Decoder = formatter.Deserialize(new MemoryStream(buf)) as Decoder;

    SendBuffer(utf8Decoder, buf2);
}

유지해야 할 값이 직접적인 Decoder 인스턴스에서 byte 배열로 바뀌었습니다.




그 외에, 또 다른 방법으로는 디코딩 시에 아직 char로 변환되지 못한 바이트 배열(UTF8의 경우 최대 6개의 바이트)이 있는 경우 다음번 디코딩 과정에 참여하도록 만드는 것입니다. 그러니까 대충 다음과 같은 과정을 거치는 것입니다.

byte[] remains = null;

{
    remains = SendBuffer(buf1);
}

{
    List<byte> buf = new List<byte>();

    if (remains != null)
    {
        buf.AddRange(remains);
    }

    buf.AddRange(buf2);

    SendBuffer(buf.ToArray());
}

이 글을 쓰기 위해 급조한 코드라 별로 마음에 들지 않아 이것은 첨부 파일로 대신합니다. 나중에 실제로 쓰게 되면 그때나 다듬어야 겠습니다. ^^; 끝!




첨부 파일은 위의 예제 순서에 따라 decoder_sample1, decoder_sample2, decoder_sample3 폴더로 나뉩니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 12/27/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 166  167  168  169  170  171  172  173  174  175  176  177  [178]  179  180  ...
NoWriterDateCnt.TitleFile(s)
589정성태6/17/200822063.NET Framework: 102. COM 개체의 이벤트를 구독하는 코드 제작 [1]
588정성태6/13/200824128VC++: 35. COM 이벤트에서 반환값을 가진 콜백 정의
587정성태6/10/200828790VS.NET IDE: 56. C#에서 아쉬운 __DATE__, __TIME__ 매크로 [2]
586정성태6/4/200826455오류 유형: 56. WPF 디자이너 - The string was not recognized as a valid DateTime [2]
585정성태6/4/200834736.NET Framework: 101. WPF - ActiveX 컨트롤 호스팅하는 방법 [2]
582정성태5/16/200826466오류 유형: 55. Windowless ActiveX controls are not supported
580정성태4/24/200825494VC++: 34. 64비트 윈도우즈에서의 이벤트 후킹
579정성태4/24/200825332VC++: 33. 변환 후의 RGS 파일 내용을 얻는 방법
577정성태4/16/200826243.NET Framework: 100. XML Serializer를 이용한 값 복사 [5]
575정성태4/7/200823452오류 유형: 54. TFS Source Control - 명령을 사용할 수 없음 [2]
574정성태3/31/200821563오류 유형: 53. TFS 연결 오류 - The workspace [...] exists on computer [...]
573정성태3/25/200825627Windows: 31. TS Web Access와 UAC [1]
570정성태3/17/200824746오류 유형: 52. TFS 연결 오류 - TF31001 [2]
569정성태3/16/200825959Team Foundation Server: 24. TFS 2008로 마이그레이션 (2) [2]
566정성태2/28/200827045.NET Framework: 99. AppDomain.GetEntryAssembly()를 우회하는 방법파일 다운로드1
564정성태2/16/200826693Windows: 30. TS Web Access + Vista SP1 [2]
563정성태2/16/200826099오류 유형: 51. Vista(UAC) + 웹 프로젝트 디버깅: System.UnauthorizedAccessException
562정성태2/12/200830302Windows: 29. Windows Server 2008 설치 [4]
561정성태1/10/200824043오류 유형: 50. IE 7 + 잘못된 HTC 파일 경로 = File not found [5]
559정성태1/1/200828795Windows: 28. Vista에서 끌어다 놓기로 GAC 등록하는 방법 [2]
558정성태1/1/200845960개발 환경 구성: 33. 32bit/64bit OLE DB Provider [1]
557정성태12/22/200724287개발 환경 구성: 32. WSCF와 VS.NET 2008
556정성태12/16/200722380기타: 22. 인기 순위 정리 : 조회수 1000 회 이상
555정성태12/16/200725400기타: 21. 인기 순위 정리 : 조회수 500 ~ 999회 글 목록
554정성태12/16/200729734기타: 20. 인기 순위 정리 : 조회수 250 ~ 499회 글 목록
553정성태12/16/200730115기타: 19. 인기 순위 정리 : 조회수 100 ~ 249회 글 목록
... 166  167  168  169  170  171  172  173  174  175  176  177  [178]  179  180  ...