2014-03-19 69 views
0

我有以下客戶端&服務器代碼。在服務器上,我收到異常「分析完成之前遇到的流結束」。在反序列化之前,我將Seek位置設置爲0。無法反序列化WCF服務中的數據(流對象)

我傳遞流作爲輸入和輸出方法

  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
      request.Method = "POST"; 
      request.ContentType = @"application/x-www-form-urlencoded"; 
      request.Accept = @"application/text;"; 

      using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream())) 
      { 
// Pass a test message 
       streamWriter.Write(Encoding.UTF8.GetBytes("test message.")); 
      } 

      WebResponse response = request.GetResponse(); 
      string result = string.Empty; 

      if (response != null) 
      { 
       using (var reader = new StreamReader(response.GetResponseStream())) 
       { 
        result = reader.ReadToEnd(); 
       } 
      } 

Server是一個RESTful服務。以下是客戶端試圖調用的服務方法。

public Stream test(Stream input) 
    { 
     MemoryStream serviceStream = new MemoryStream(); 
     byte[] buffer = new byte[10000]; 
     int bytesRead = 0; 

     do 
     { 
      bytesRead = input.Read(buffer, 0, buffer.Length); 
      serviceStream.Write(buffer, 0, bytesRead); 
     } while (bytesRead > 0); 

     serviceStream.Position = 0; 

     var binForm = new BinaryFormatter(); 

     // I get exception at this line "End of Stream encountered before parsing was completed." 
     string obj = (string)binForm.Deserialize(serviceStream); 

     string result = "test is called : "+obj; 

     return new MemoryStream(Encoding.UTF8.GetBytes(result)); 
    } 

有人能告訴我這裏有什麼問題嗎?

Annu Mittal

+0

哪條線你得到這個錯誤? – Sajeetharan

+0

string obj =(string)binForm.Deserialize(serviceStream); –

回答

1

我認爲這個問題是在你將數據發送到服務器的方式。在客戶端代碼只是更改以下行

streamWriter.Write(Encoding.UTF8.GetBytes("test message.")); 

streamWriter.Write("test message."); 

我相信目前它正在通過「system.Byte []」作爲字符串到服務器。

0

不要使用您的對象,而是使用對象類型。

YourObjectType test = (YourObjectType)binForm.Deserialize(serviceStream); 

確保這些,

(I)的序列化完成,該序列類型相匹配反序列型

(二)你序列化流來真正完成序列化,以一個Stream.Flush()或類似的東西。

(III)也把try/catch語句

+0

我僅在反序列化時使用對象類型 –