我尝试编写一个Java服务器套接字和一个客户端写入C#发送和接收来自服务器的数据。 我想压缩gzip数据:
Java Socket Server:
GZIPInputStream zip = new server.getInputStream());
while (true) {
int c;
c = zip.read();
if (c == -1)
break;
System.out.print((char) c);
}
String resp = "hello";
byte[] dataToCompress = resp.getBytes();
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(dataToCompress.length);
GZIPOutputStream zipStream = new GZIPOutputStream(byteStream);
zipStream.write(dataToCompress);
byte[] compressedData = byteStream.toByteArray();
server.getOutputStream().write(compressedData);
C#套接字客户端:
TcpClient client = new TcpClient();
// 1. connect
client.Connect("127.0.0.1", PORT_NUMBER);
Stream stream = client.GetStream();
string str = "hello";
// 2. send
byte[] input = Encoding.UTF8.GetBytes(str);
byte[] data = new byte[BUFFER_SIZE];
//data = Compress(input);
data = Zip(input);
//data = input;
stream.Write(data, 0, data.Length);
// 3. receive
data = new byte[BUFFER_SIZE];
stream.Read(data, 0, BUFFER_SIZE);
string ss = UnZip(data);
Console.WriteLine(ss);
public static byte[] Zip(byte[] byteArray)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms,
System.IO.Compression.CompressionMode.Compress);
//Compress
sw.Write(byteArray, 0, byteArray.Length);
//Close, DO NOT FLUSH cause bytes will go missing...
sw.Close();
//Transform byte[] zip data to string
byteArray = ms.ToArray();
return byteArray;
}
public static string UnZip(byte[] byteArray)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray);
System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms,
System.IO.Compression.CompressionMode.Decompress);
//Reset variable to collect uncompressed result
byteArray = new byte[byteArray.Length];
//Decompress
int rByte = sr.Read(byteArray, 0, byteArray.Length);
//Transform byte[] unzip data to string
System.Text.StringBuilder sB = new System.Text.StringBuilder(rByte);
//Read the number of bytes GZipStream red and do not a for each bytes in
//resultByteArray;
for (int i = 0; i < rByte; i++)
{
sB.Append((char)byteArray[i]);
}
sr.Close();
ms.Close();
sr.Dispose();
ms.Dispose();
return sB.ToString();
}
但它出错了。当我将数据从C#发送到java时,它正确地进行压缩和解压缩,但是当我将数据从Java发送到C#时,它会产生异常并且我将字节数组数据压缩为C#并将字节数组压缩为Java,这是不同的。
我的代码是如何正确工作的?