繁体   English   中英

C#套接字消息解压缩

[英]C# socket message decompression

我是C#世界的新手。 我正在使用它来快速部署解决方案来捕获以这种形式出现的实时订阅源(为了清晰起见,大括号):{abcde} {CompressedMessage},其中{abcde}构成5个字符,表示压缩消息的长度。 CompressedMessage使用XCeedZip.dll进行压缩,需要使用dll的uncompress方法解压缩。 uncompress方法返回一个整数值,表示成功或失败(各种类型,例如没有许可证失败,解压缩失败等)。 我收到故障1003 http://doc.xceedsoft.com/products/XceedZip/以获取uncompress方法返回值的参考。

while(true){    
byte[] receiveByte = new byte[1000];
sock.Receive(receiveByte);
string strData =System.Text.Encoding.ASCII.GetString(receiveByte,0,receiveByte.Length);
string cMesLen = strData.Substring(0,5); // length of compressed message;
string compressedMessageStr = strData.Substring(5,strData.Length-5);
byte[] compressedBytes = System.Text.Encoding.ASCII.GetBytes(compressedMessageStr);
//instantiating xceedcompression object     
XceedZipLib.XceedCompression obXCC = new XceedZipLib.XceedCompression();
obXCC.License("blah");
// uncompress method reference http://doc.xceedsoft.com/products/XceedZip/
// visual studio displays Uncompress method signature as Uncompress(ref object vaSource, out object vaUncompressed, bool bEndOfData)
object oDest;
object oSource = (object)compressedBytes;
int status = (int) obXCC.Uncompress(ref oSource, out oDest, true);
Console.WriteLine(status); /// prints 1003 http://doc.xceedsoft.com/products/XceedZip/
}                                                       

所以基本上我的问题归结为调用uncompress方法和传递参数的正确方法。 我在.net世界中处于不熟悉的领域,所以如果这个问题非常简单,我不会感到惊讶。

谢谢你的回复..

##################################### 更新

我现在正在做以下事情:

 int iter = 1; int bufSize = 1024; byte[] receiveByte = new byte[bufSize]; while (true){ sock.Receive(receiveByte); //fetch compressed message length; int cMesLen = Convert.ToInt32(System.Text.Encoding.ASCII.GetString(receiveByte,0,5)); byte[] cMessageByte = new byte[cMesLen]; if (i==1){ if (cMesLen < bufSize){ for (int i = 5; i < 5+cMesLen; ++i){ cMessageByte[i-5] = b[i]; } } } XceedZipLib.XceedCompression obXCC = new XceedZipLib.XceedCompression(); obXCC.License("blah"); object oDest; object oSource = (object) cMessageByte; int status = (int) obXCC.Uncompress(ref oSource, out oDest, true); if (iter==1){ byte[] testByte = objectToByteArray(oDest); Console.WriteLine(System.Text.Encoding.ASCII.GetString(testByte,0,testByte.Length)); } } private byte[] objectToByteArray(Object obj){ if (obj==null){ return null; } BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms,obj); return ms.ToArray(); } 

问题是testByte writeline命令打印出乱码。 关于如何向前推进的任何建议? uncompress的状态变量是好的,现在等于0。

总是,第一个错误是没有看到Receive的返回值; 你不知道你刚读了多少数据,也不知道它是否构成了整个信息。

通过将整个数据视为ASCII,您似乎已经破坏了消息的有效负载。 您应该使用GetString 指定仅使用5个字节 ,而不是在整个缓冲区上执行GetString

正确的过程:

  • 继续调用Receive (缓冲数据,或增加偏移量并减少计数),直到你有至少5个字节
  • 处理这5个字节以获得有效负载长度
  • 继续调用Receive (缓冲数据,或增加偏移量并减少计数),直到至少有效负载长度为止
  • 处理有效负载而无需转换为ASCII

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM