简体   繁体   English

如何在通过ChannelFactory创建的WCF服务上设置回调通道?

[英]How to set up callback channel on WCF service created via ChannelFactory?

I need my WCF service to raise events to the clients. 我需要我的WCF服务来向客户端发送事件。 I've read that that happens through callback channel, and I've implemented it in the following manner: Service interfaces: 我已经读过通过回调通道发生的事情,我已经按照以下方式实现了它:服务接口:

public interface IServiceCallback
{
    [OperationContract(IsOneWay = true)]
    void OnNewAlert(Alert a);
    [OperationContract(IsOneWay = true)]
    void OnProductEdited(Product p);
    [OperationContract(IsOneWay = true)]
    void OnHighlightChanged(Dictionary<User, List<Product>> highlighted);
    [OperationContract(IsOneWay = true)]
    void OnCatalogUpdated();


    event EventHandler NewAlert;
    event EventHandler ProductEdited;
    event EventHandler HighlightChanged;
    event EventHandler CatalogUpdated;
}
[ServiceContract(CallbackContract = typeof(IServiceCallback))]
public interface IService : IDisposable
{
    [OperationContract]
    List<Product> GetProducts(Predicate<Product> match = null, int limit = 0, string username = null);
    [OperationContract]
    Product GetProduct(Predicate<Product> match, string username = null);
    [OperationContract]
    Product GetRandomProduct(Predicate<Product> match = null, string username = null);
    [OperationContract]
    int GetFlagIndex(string flagName);
    [OperationContract]
    void SetFlag(string pid, string flagName, bool value);
    [OperationContract]
    List<Alert> GetAlerts(string username);
    [OperationContract]
    void DismissAlert(Alert alert, String username);
    [OperationContract]
    void HighlightProduct(List<string> pids, string user);
    [OperationContract]
    void EditProduct(string pid, Dictionary<string, object> fieldValues, string username = null);
    [OperationContract]
    void AttachModule(IModule m);
    [OperationContract]
    void Ping();

    event EventHandler NewAlert;
    event EventHandler ProductEdited;
    event EventHandler HighlightChanged;
    event EventHandler CatalogUpdated;
}

Service implementation: 服务实施:

namespace Service
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Reentrant)]
public class ServiceInstance : IService
{
    List<IServiceCallback> callbackChannels = new List<IServiceCallback>();
    //other vars

    public ServiceInstance()
    {
            //lots of stuff here
    }

    private User SignalUser(string username)
    {
        if (username == null)
            return null;

        IServiceCallback channel = OperationContext.Current.GetCallbackChannel<IServiceCallback>();
        if (!callbackChannels.Contains(channel)) //if CallbackChannels not contain current one.
        {
            callbackChannels.Add(channel);
        }

        User user = knownUsers.Find(p => p.username == username);
        if (user == null)
        {
            user = new User();
            user.username = username;
            user.highlighColor = Color.FromArgb(r.Next(0, 128), r.Next(0, 128), r.Next(0, 128));
            knownUsers.Add(user);
            foreach (KeyValuePair<Alert, List<User>> kvp in alerts)
            {
                kvp.Value.Add(user);
            }
        }
        user.lastOnline = DateTime.Now;
        if(!onlineUsers.Contains(user))
            onlineUsers.Add(user);

        return user;
    }

    //lots of other things here
}
}

Callback implementation on Client: 客户端的回调实现:

class ServiceEventHandler : IServiceCallback
{
    public event EventHandler NewAlert;
    public event EventHandler ProductEdited;
    public event EventHandler HighlightChanged;
    public event EventHandler CatalogUpdated;

    public void OnCatalogUpdated()
    {
        CatalogUpdated?.BeginInvoke(null, null, null, null);
    }

    public void OnHighlightChanged(Dictionary<User, List<Product>> highlighted)
    {
        HighlightChanged?.BeginInvoke(highlighted, EventArgs.Empty, null, null);
    }

    public void OnNewAlert(Alert a)
    {
        NewAlert?.BeginInvoke(a, EventArgs.Empty, null, null);
    }

    public void OnProductEdited(Product p)
    {
        ProductEdited?.BeginInvoke(p, EventArgs.Empty, null, null);
    }
}

But here is my problem: On the client side, I'm supposed to pass it to the service like this: 但这是我的问题:在客户端,我应该将它传递给这样的服务:

EventHandler eventHandler = new EventHandler();
MyServiceClient client = new MyServiceClient(new InstanceContext(eventHandler));

according to this StackOverflow answer: https://stackoverflow.com/a/1143777/2018696 根据StackOverflow的回答: https ://stackoverflow.com/a/1143777/2018696

But I don't connect to my service like this, because my client does not know about the implementation of the service, it only knows the two interfaces! 但我没有像这样连接到我的服务,因为我的客户端不知道服务的实现,它只知道这两个接口! So I connect like this: 所以我这样连接:

    public static IService GetService(string serviceAddress)
    {
        Uri service_uri = new Uri(serviceAddress);
        var endpoint = new EndpointAddress(service_uri, new[] { AddressHeader.CreateAddressHeader(settings["username"], "", "") });
        IService service = ChannelFactory<IService>.CreateChannel(new BasicHttpBinding(), endpoint);
        return service;
    }

So how do I get the callbacks to work? 那么如何让回调起作用呢?

UPDATE: 更新:

Ok, so as proposed by a comment, I replaced ChannelFactory with DuplexChannelFactory and BasicHTTPBinding with WsDualHTTPBinding, and I don't get response from the server. 好吧,正如评论所提出的,我用DuplexChannelFactory替换了ChannelFactory,用WsDualHTTPBinding替换了BasicHTTPBinding,我没有得到服务器的响应。 I do get response with BasicHTTPBinding if I scratch the callback handler. 如果我刮开回调处理程序,我会得到BasicHTTPBinding的响应。 So essentially: 基本上:

[ServiceContract]
BasicHttpBinding();
ChannelFactory<IService>.CreateChannel(binding, endpoint);

^ this works ^这有效

[ServiceContract(CallbackContract = typeof(IServiceCallback))]
WSDualHttpBinding(WSDualHttpSecurityMode.None);
DuplexChannelFactory<IService>.CreateChannel(new InstanceContext(handler), binding, endpoint);

^ this doesn't. ^这不。

It works on localhost, but not on LAN or Internet. 它适用于localhost,但不适用于LAN或Internet。 Firewalls are off on both server and client. 服务器和客户端都禁用防火墙。 I'm getting 60 second timeout when I try to contact the server. 当我尝试联系服务器时,我得到60秒超时。

I have discovered that my connection issues are due to no port forwarding being set on the path to the client. 我发现我的连接问题是由于在客户端的路径上没有设置端口转发。 Since I can't ensure proper port access to clients, I have reverted back to non-callback model, and will be using regular request from clients to receive accumulated event data from the service. 由于我无法确保对客户端进行正确的端口访问,因此我已恢复为非回调模型,并将使用来自客户端的常规请求从服务接收累积的事件数据。 Probably not efficient, but a foolproof method that seems to be working so far. 可能效率不高,但到目前为止似乎是一种万无一失的方法。 Thank you all for your attention. 谢谢大家的关注。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM