Here's what I have so far:
IService:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using S开发者_JS百科ystem.ServiceModel;
namespace ServiceLibrary
{
[ServiceContract(SessionMode = SessionMode.Allowed, CallbackContract = typeof(IServiceCallback))]
public interface IService
{
[OperationContract(IsOneWay = false, IsInitiating = true, IsTerminating = false)]
void Join(string userName);
}
interface IServiceCallback
{
[OperationContract(IsOneWay = true)]
void UserJoined(string senderName);
}
}
Service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace ServiceLibrary
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service:IService
{
IServiceCallback callback = null;
public void Join(string userName)
{
callback = OperationContext.Current.GetCallbackChannel<IServiceCallback>();
}
}
}
Just a simple string passed from one client to another.
You can't actively "push" a string from one WCF client to another - unless you use the peer-to-peer binding.
But what you're trying to do appears to be somewhat along the lines of the publish/subscribe model: one node publishes information (the server - maybe getting it from one of the clients), and any number of subscribers then receive that information.
There are a number of approaches in WCF on how to do this - duplex communication, MSMQ or Windows Azure ServiceBus messaging - the approaches are quite varied.
Here are a few articles with various approaches to get you started:
- Design Patterns: List-Based Publish-Subscribe
- Using Callback Contracts in WCF for Asynchronous Publish/Subscribe Event-Style Communication
- Building a Pub/Sub Message Bus with WCF and MSMQ
- Windows Azure – Service Bus Publish/Subscribe Example
but you'll find plenty more when you search for "WCF publish subscribe pattern" either on Google or Bing.
Looks like you already use duplex binding. Just keep a list of callbacks(subscribers) in some static Collection (static because you use per-session instances). When somebody calls "join" just iterate through that collection and call UserJoined
for each subscriber.
private static List<IServiceCallback> subscribers = new List<IServiceCallback>();
public void Join(string userName)
{
IServiceCallback callback = OperationContext.Current.GetCallbackChannel<IServiceCallback>();
foreach (var serviceCallback in subscribers)
{
serviceCallback.UserJoined(userName);
}
subscribers.Add(callback);
}
精彩评论