Microsoft MVP성태의 닷넷 이야기
.NET Framework: 136. 자바와 닷넷의 압축 호환 [링크 복사], [링크+제목 복사],
조회: 32190
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)

자바와 닷넷의 압축 호환


이전에 썼던 글이 바로 이 글을 쓰기 위한 선행 작업이었습니다.

Deflate, GZip, Zip
; https://www.sysnet.pe.kr/2/0/723

며칠 전에, 자바로 구현된 서버 측 서비스와 연동해야 할 일이 있었습니다. 작업 중의 하나는 압축 데이터를 서로 교환하는 것이었는데, .NET에서 압축된 데이터를 Java에서 풀지 못하는 일이 발생했습니다. 문제가 발생한 이후, 우리 쪽은 GZipStream을 사용한다고 했고 약간의 시간이 흐르고 Java 측 개발자는 그에 맞춰서 조정을 해주었습니다. 그래서 연동이 되었지요. ^^

그 상황에서는 다행히 Java 측 개발자가 "맞춰주는" 분위기여서 ^^ 그렇게 했지만, 사실 상황에 따라서는 이것이 반대로 되어야 합니다. 그런 경우에 여러분은 어떻게 조정을 해주시겠습니까?

해답은 간단합니다. 바로 "Deflate, GZip, Zip" 글의 내용을 이해하고 있으면 그 부분은 쉽게 해결이 됩니다. 즉, 자바에서 "DeflaterOutputStream"을 사용해서 압축을 했는데 닷넷 측에서 "GZipStream"을 이용해서 압축을 해제하는 식이면 오류가 발생하게 되는 것입니다. 전형적으로 다음과 같은 오류가 발생합니다.

[그림 1: 압축 해제 오류]
gzipstream_gzipheader_1.png

"
The magic number in GZip header is not correct. Make sure you are passing in a GZip stream.

"



왜인지 아시겠죠? 자바의 Deflate 압축에는 헤더 데이터가 없는데, 닷넷의 GZipStream에서 헤더를 읽어내려고 시도하기 때문에 위와 같은 예외가 발생하는 것입니다. (물론, 그 반대의 경우 - 닷넷에서 DeflateStream으로 압축하고 자바에서 GZIPInputStream으로 압축을 해제할 때도 오류가 발생하겠지요.)




실제로, 연동을 해보는 코딩을 연습삼아 만들어 보기로 했습니다. 우선, 서버 측 압축 소스 코드를 공개한 다음의 글을 참조해서 이클립스로 간단하게 프로젝트를 만들었습니다.

http 압축/해제
; http://yally93.egloos.com/2148475

보시는 것처럼, DeflaterOutputStream / InflaterInputStream을 사용했기 때문에 "raw 압축 데이터"만을 다룰 테고 닷넷 측 역시 DeflateStream으로 받아줘야 합니다.

일단 자바 측 소스 코드는 위의 글에서 조금 변경하여 다음과 같이 작성했습니다.

import java.io.*;
import java.util.zip.*;

public class FileDeflater 
{
	public String zipping(String param) 
	{
		try {
			byte[] unzip = param.getBytes();
			ByteArrayInputStream bif = new ByteArrayInputStream(unzip);

			ByteArrayOutputStream zipbof = new ByteArrayOutputStream();
			DeflaterOutputStream dos = new DeflaterOutputStream(zipbof);
			int position = 0;

			for (int read_byte = 0; (read_byte = bif.read()) != -1; position++) 
			{
				dos.write(read_byte);
			}
			 
			dos.finish();
			zipbof.flush();

			byte[] zipbyteArray = zipbof.toByteArray();

			return new sun.misc.BASE64Encoder().encode(zipbyteArray);
		} 
		catch (Exception ex) 
		{
			return null;
		}
	}
}

public class testApp 
{
	public static void main(String[] args) 
	{
		FileDeflater a = new FileDeflater();
		String text = a.zipping("u cant watch korean 한글");
		System.out.println (text);		
	}

}

순서는 압축한 다음에 base64 인코딩을 했기 때문에 닷넷 측에서는 base64 디코딩을 먼저 하고 압축 해제를 하면 되므로 다음과 같이 작성할 수 있습니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string txt = "eJwrVUhOzCtRKE8sSc5QyM4vSk3MUzh+ceNtAHCQClc="; // 자바의 "u cant watch korean 한글" 압축 결과

            byte[] compressedBytes = Convert.FromBase64String(txt);

            MemoryStream ms = new MemoryStream(compressedBytes);
            byte[] decompressedBuffer;

            using (DeflateStream zipStream = new DeflateStream(ms, CompressionMode.Decompress))
            {
                decompressedBuffer = Program.ReadAllBytesFromStream(zipStream);
            }

            string plainText = Encoding.Default.GetString(decompressedBuffer);
            Console.WriteLine(plainText);
        }

        public static byte[] ReadAllBytesFromStream(Stream stream)
        {
            MemoryStream ret = new MemoryStream();

            Byte[] buffer = new Byte[2048];
            int size;

            while (true)
            {
                size = stream.Read(buffer, 0, buffer.Length);
                if (size > 0)
                {
                    ret.Write(buffer, 0, size);
                }
                else
                {
                    break;
                }
            }

            ret.Flush();
            ret.Close();
            return ret.ToArray();
        }
    }
}

그런데, 실행하고 나면 의외로 다음과 같은 예외가 발생합니다.

Unhandled Exception: System.IO.InvalidDataException: Block length does not match with its complement.
   at System.IO.Compression.Inflater.DecodeUncompressedBlock(Boolean& end_of_block)
   at System.IO.Compression.Inflater.Decode()
   at System.IO.Compression.Inflater.Inflate(Byte[] bytes, Int32 offset, Int32 length)
   at System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset, Int32 count)
   at ConsoleApplication1.Program.ReadAllBytesFromStream(Stream stream) in D:\temp\Program.cs:line 40
   at ConsoleApplication1.Program.Main(String[] args) in D:\temp\Program.cs:line 24
Press any key to continue . . .

구글 검색을 해서 찾아낸 결과,

"Block length does not match with its complement." in DeflateStream
; http://www.chiramattel.com/george/blog/2007/09/09/deflatestream-block-length-does-not-match.html

이런 문제가 있었군요. 자바 측의 DeflaterOutputStream은 zlib 스펙을 정의한 RFC 1950을 따르는 반면 닷넷 측의 DeflateStream은 액면 그대로 deflate 스펙을 정의한 RFC 1951을 따르기 때문에 발생하는 것입니다. 다행히 그 차이는 크지 않아서 단순히 처음의 2byte만을 건너뛰면 되어서 닷넷 측 소스 코드를 다음과 같이 변경해 주면 됩니다.

static void Main(string[] args)
{
    string txt = "eJwrVUhOzCtRKE8sSc5QyM4vSk3MUzh+ceNtAHCQClc=";

    byte[] compressedBytes = Convert.FromBase64String(txt);

    MemoryStream ms = new MemoryStream(compressedBytes);
    ms.Position = 2;
    byte[] decompressedBuffer;

    using (DeflateStream zipStream = new DeflateStream(ms, CompressionMode.Decompress))
    {
        decompressedBuffer = Program.ReadAllBytesFromStream(zipStream);
    }

    string plainText = Encoding.Default.GetString(decompressedBuffer);
    Console.WriteLine(plainText);
}




그 외에, 주의해야 할 사항이 하나 있다면 바로 문자열의 인코딩 방식입니다. 만약 자바에서 다음과 같이 문자열에 대한 바이트를 구했다면,

byte[] unzip = param.getBytes();

이때의 인코딩 방식은 기본적으로 시스템에서 설정된 코드 페이지가 됩니다. 처음에 저는 자바의 문자열도 Unicode를 기본으로 채택하고 있기 때문에 위와 같이 기본 getBytes()를 호출하는 경우 Unicode 인코딩을 따른다고 생각했는데 그렇지 않았습니다. 즉, 한글 윈도우즈의 경우에 DBCS로 "ks_c_5601-1987"이 되는 것입니다.

위와 동일한 코드가 닷넷에서는 다음과 같이 적용됩니다.

byte [] encoded = Encoding.Default.GetBytes(txt);

다들 아시겠지만 이것은 전혀 바람직하지 않은 코딩 방법입니다. 서버와 클라이언트가 동일한 코드 페이지로 구성되어 있다는 가정을 해서는 안 됩니다. 대신에, 아래와 같이 문자열 인코딩을 UTF-8이나 Unicode로 명시적으로 지정하는 것이 좋습니다.

=== 자바: UTF-8 인코딩 바이트 배열 구하기 ===
byte[] unzip = param.getBytes("UTF-8");

=== 닷넷: UTF-8 인코딩된 바이트로부터 문자열 구하기 ===
string plainText = Encoding.UTF8.GetString(decompressedBuffer);

이를 테스트한 소스 코드를 첨부해 두었습니다. (자바 프로젝트는 Eclipse로 만들었고, 닷넷 프로젝트는 Visual Studio 2008입니다.)



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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/3/2023]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13440정성태11/11/20232517Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20233104닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232674닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232856닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20233120닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20233017닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232782스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232472스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232553오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232944스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232785닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233063닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233162닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233342닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233490스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233257닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233244스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233397닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233483닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235799스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233286스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20234000닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233536닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233299오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233804닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233580디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...