Microsoft MVP성태의 닷넷 이야기
.NET Framework: 136. 자바와 닷넷의 압축 호환 [링크 복사], [링크+제목 복사]
조회: 32173
글쓴 사람
정성태 (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)
13604정성태4/22/2024194오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024248닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024528닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024700닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024708닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024800닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024794닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024783닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241033닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241046닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241064닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241073닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241214C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241187닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241078Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241149닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241237닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241165오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241316Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241104Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241058개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241175Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241432Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241604개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241165닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...