2010-06-10 190 views
1

我有一個簡單的Web服務運行,我有一個控制檯應用程序客戶端使用該服務。我確實遇到了一些問題,我得到了這個社區一些優秀人士的幫助。消費WCF Web服務

我還有一個問題:如果我想在循環中從客戶端調用服務,它不起作用。它只在第一次工作,然後它一直在等待。爲什麼會發生這種情況,我該如何解決這個問題。

代碼:

namespace WebService 
{ 
    [ServiceContract] 
    public interface IService 
    { 
    [OperationContract(Name="Result")] 
    [WebGet(UriTemplate = "/")] 
    Stream Result(); 
    } 

    public class Service:IService 
    { 
     public Stream Result() 
     { 
      // read a file from the server and return it as stream 
     } 
    } 
} 

The client: 
namespace WebServiceClient 
{ 
    [ServiceContract] 
    public interface IService 
    { 
    [OperationContract(Name="Result")] 
    [WebGet(UriTemplate = "/")] 
    Stream Result(); 
    } 

} 

static void Main() 
{ 

    Console.WriteLine("Press enter when the service is available"); 
    Console.ReadLine(); 

    // creating factory 
    HttpChunkingBinding binding = new HttpChunkingBinding(); 
    binding.MaxReceivedMessageSize = 0x7fffffffL; 

    ChannelFactory<WebServiceClient.IService> factory = new ChannelFactory<WebServiceClient.IService> 
      (binding, new EndpointAddress("http://localhost/WebService/Service")); 

      WebServiceClient.IService service = factory.CreateChannel(); 

     for(int i = 0; i < 10; i++) 
     { 
      Stream s = service.Result(); 
      // write this stream to a file and close the stream 
     } 

      //Closing our channel. 
      ((IClientChannel)service).Close(); 

} 

感謝,

+3

帖子你的代碼和異常消息。 – Juliet 2010-06-10 19:36:02

+0

你能發表一些代碼嗎?調試web服務的一個好方法是使用Fiddler觀察HTTP流量。 – Alan 2010-06-10 19:36:50

+0

你使用什麼技術? – tster 2010-06-10 19:40:53

回答

0

您還沒有發佈的代碼,所以我想給胡亂猜測:

您有打開的連接的最大數目設置爲1並在循環中打開到web服務的連接,但不會將連接作爲循環的一部分關閉。這會造成第二次迭代正在等待第一次連接超時(可能設置爲10分鐘)的情況。

+0

我認爲你正在進行一些操作,但他顯然不是手動打開通道;更可能的是,他沒有正確關閉流,這將迫使連接保持開放。 – Aaronaught 2010-06-10 20:21:42

0

看起來像是在嘗試實施分塊頻道。 看看這個定義如何實現它的article

接近文章底部,它explains如何設置WCF示例項目。示例項目中有一個大塊的例子。

我很確定連接沒有關閉,因爲您還沒有完成讀取所有數據。因爲你是塊,所以並不是所有的數據都在同一時間交付。你問一個塊,處理它,然後要求另一個塊。

好運,

帕特里克

+0

FWIW,在我的WCF REST項目中(這就是AFAICT)我不需要使用外部組塊通道(如SDK中的示例),堆棧已經支持接受和返回Stream就好了(並且它已經工作了對我很好)。 FWIW,AFAICT它確實使用http分塊來實現Stream接口(與Fiddler快速檢查),但他們會爲你抽象它:) – 2010-06-11 06:44:01

+0

有趣的...在這種情況下,也許@Debby可以嘗試使用WebHttpBinding而不是示例代碼中使用的HttpChunkingBinding。如果REST服務在後臺實現分塊,它應該可以工作。試試@Debby吧,讓我們知道它是否有效。感謝您的輸入@James Manning – Patrick 2010-06-11 15:02:53

1

只是一個猜測,但聽起來就像是有事情做與你的連接不打烊服務...嘗試以下操作:

for(int i = 0; i < 10; i++) 
    { 
     ChannelFactory<WebServiceClient.IService> factory = 
      new ChannelFactory<WebServiceClient.IService>(
       binding, 
       new EndpointAddress("http://localhost/WebService/Service")); 

     WebServiceClient.IService service = factory.CreateChannel(); 
     using(service as IDsposable) 
     { 
      using(MemoryStream s = service.Result() as MemoryStream) 
      { 
      // write this stream to a file 
      } 
     } 
    }