我认为首先回答这个问题会让生活变得更轻松:
我怎么知道“这个”客户是什么?
OperationContext.Current.GetCallbackChannel<T>
对于服务收到的每个调用,都会有一个进行调用的客户端通道,这将为您提供仅进行该调用的客户端的回调通道,这是您能够区分客户端的简单方法。
关于整个场景的方法,我首先会存储一个列表subscribers
在静态的dictionary
正如您自己建议的那样,还要保留每个客户端回调实例及其用户名:
private static Dictionary<IPriceChangeCallback, string> subscribers = new Dictionary<IPriceChangeCallback, string>();
Where IPriceChangeCallback
是您的回调合约,字符串可以是唯一的用户名或任何标识符。现在您已经具备了区分客户端的基本能力,例如,假设您要将最后收到的消息发布给除发送消息的客户端之外的每个客户端,您将:
lock (subscribers)
{
foreach (var _subscriber in subscribers)
{
if (OperationContext.Current.GetCallbackChannel<IPriceChangeNotification>() == _subscriber.Key)
{
//if the person who sent the last message is the current subscriber, there is no need to
//publish the message to him, so skip this iteration
continue;
}
else
{
//GetCurrrentClient is a handy method, you can optionally include this
//in your callbacks just to let your clients know who exactly sent the publication
_subscriber.Key.PriceChangeCallback(e.Item, e.Price, e.Change, GetCurrentClient());
}
}
}
或者根据用户名来区分您的客户,理想情况下您也应该在数据库中拥有该用户名:
lock (subscribers)
{
foreach (var _subscriber in subscribers)
{
if(_subscriber.Value == "Jimmy86"))
{
//Identify a specific client by their username and don't send the notification to him
//here we send the notification to everyone but jimmy86
continue;
}
else
{
_subscriber.Key.PriceChangeCallback(e.Item, e.Price, e.Change, GetCurrentClient());
}
}
}
同样,每当您想要找出谁调用了服务操作,并告诉您的客户谁发送了该特定消息时,请使用GetCurrentClient()
我之前提到的方法:
private string GetCurrentClient()
{
return clients[OperationContext.Current.GetCallbackChannel<IPriceChangeNotification>()];
}
这是正确的方法吗?
我不确定上面的方法是否明智,但每当我想保留客户端列表并对其调用某些方法时,我都会这样做。
客户是否应该通过我将存储的“订阅”方法向我发送凭据?
是的,这是一种常见的做法。有一个Subscribe()
对您的服务进行操作,这将是您的客户想要加入您的服务时调用的第一个方法:
[OperationContract(IsOneWay = true)]
public void Subscribe(string username)
{
lock (subscribers)
{
subscribers.Add(OperationContext.Current.GetCallbackChannel<IPriceChangeNotification>(), username);
}
}
几个月前我正在开发 Pub/Sub Silverlight 服务,我发现本文 http://tomasz.janczuk.org/2009/07/pubsub-sample-using-http-polling-duplex.html这是附带视频 http://channel9.msdn.com/Shows/SilverlightTV/Duplex-Communication-with-WCF-in-Silverlight-4-Silverlight-TV-34是无价的。