您的位置:首页 > 其它

为 Silverlight 客户端生成双工服务

2011-03-24 21:36 169 查看
本主题描述了如何创建可与 Silverlight 客户端进行通信的双工 Windows Communication Foundation (WCF)
服务。双工服务将保留到 Silverlight
客户端的回调通道,它允许该服务对此客户端进行调用。双工服务具有许多应用程序,例如,包括用于即时消息传递的聊天服务程序或用于向客户端发送通知的监视服务。本示例提供一项服务,该服务允许客户端按名称对指定数量的产品项进行排序。该服务将模拟订单处理过程,然后使用订单的状态回调客户端。

在双工消息传递中,服务和客户端都公开服务协定,这会指定服务和客户端分别向对方所公开的操作。在此示例中,我们使用下面一对服务协定。客户端将对服务调用
Order 方法,而服务将对客户端调用 Receive 方法。

[ServiceContract(Namespace="Silverlight", CallbackContract = typeof(IDuplexClient))]
public interface IDuplexService
{
[OperationContract]
void Order(string name, int quantity);
}

[ServiceContract]
public interface IDuplexClient
{
[OperationContract(IsOneWay = true)]
void Receive();
}


请注意,CallbackContract
属性用于指定回调客户端的服务协定。

另外请注意,对于作为回调协定一部分的每个客户端方法,IsOneWay 属性在 OperationContractAttribute
中也必须设置为 true。此属性表示这些操作不返回答复消息。

创建 WCF 双工服务以使用 Silverlight

打开 Visual Studio 2010。

"文件"菜单中依次选择"新建""项目",从您要在其中进行编码的语言(C# 或 Visual
Basic)组中左侧列出的"项目类型"中指定"WCF"。然后,从右侧的"模板"中选择"WCF
服务应用程序"
,在下面的"名称"框中将其命名为
DuplexService,再单击"确定"

使用针对 DuplexService 命名空间的下列代码替换 IService1.cs 文件的默认内容。此代码使用
interfaces 来定义服务和客户端所用的协定。

Service1.svc.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading;

namespace DuplexService
{
public class OrderService : IDuplexService
{
IDuplexClient client;
string orderName;
int orderQuantity;

public void Order(string name, int quantity)
{
// Grab the client callback channel.
client = OperationContext.Current.GetCallbackChannel<IDuplexClient>();
orderName = name;
orderQuantity = quantity;

// Pretend the service is processing and will call the client
// back in 5 seconds.
using (Timer timer = new Timer(new TimerCallback(CallClient), null, 5000, 5000))
{
Thread.Sleep(11000);

}
}

bool processed = false;

private void CallClient(object o)
{
Order order = new Order();
order.Payload = new List<string>();

// Process the order.
if (processed)
{
// Pretend the service is fulfilling the order.
while (orderQuantity-- > 0)
{
order.Payload.Add(orderName + orderQuantity);
}

order.Status = OrderStatus.Completed;

}
else
{
// Pretend the service is processing the payment.
order.Status = OrderStatus.Processing;
processed = true;
}

// Call the client back.
client.Receive(order);

}

}

public class Order
{
public OrderStatus Status { get; set; }
public List<string> Payload { get; set; }
}

public enum OrderStatus
{
Processing,
Completed
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: