[WCF] 實作雙向的WCF Service (Duplex Service)

  • 5796
  • 0
  • 2009-06-03

[WCF] 實作雙向的WCF Service (Duplex Service)

(本範例使用Visual studio 2008實作)

1.新增一個WCF Service,取名為DuplexServiceSample

WCF01  WCF02

2.重新命名之後,架構圖如下

WCF03

3.定義服務合約 (Service Contract)

 


[ServiceContract(Namespace = "", 
                 SessionMode = SessionMode.Required,
                 CallbackContract = typeof(IDuplexServiceCallback))]
public interface IDuplexService
{    
    [OperationContract]
    string SendMessage(string message);      
}

public interface IDuplexServiceCallback
{
    [OperationContract(IsOneWay = true)]
    void OnSendMessage(string message);    
}

4.實作服務合約

 


[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class DuplexService : IDuplexService
{    
    IDuplexServiceCallback Callback
    {
        get
        {
            return OperationContext.Current.GetCallbackChannel<IDuplexServiceCallback>();
        }
    }

    public string SendMessage(string message)
    {
        Callback.OnSendMessage(message);
        return string.Format("You have send message : {0}",message);
    }
}

5.修改DuplexService.svc

 


<%@ ServiceHost Language="C#" Debug="true" Service="DuplexService" CodeBehind="~/App_Code/Duplex.cs" %>

6.修改Web.config

 


<?xml version="1.0"?>
<configuration>
<system.serviceModel>
		<services>
			<service behaviorConfiguration="ServiceBehavior" name="DuplexService">
				<endpoint address="" binding="wsDualHttpBinding" bindingConfiguration="" contract="IDuplexService">
					<identity>
						<dns value="localhost"/>
					</identity>
				</endpoint>
				<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
			</service>
		</services>
		<behaviors>
			<serviceBehaviors>
				<behavior name="ServiceBehavior">
					<serviceMetadata httpGetEnabled="true"/>					
					<serviceDebug includeExceptionDetailInFaults="false"/>
				</behavior>
			</serviceBehaviors>
		</behaviors>
	</system.serviceModel>
</configuration>

7.按下F5,可以看到WCF Service成功的運行

WCF04