wcf回调,从Service类外部调用客户端

时间:2014-09-08 14:44:08

标签: c# wcf callback nettcpbinding

所以我有一个拥有多个客户端的selfhostet服务(netTcpBinding)。 现在我想通过程序其他部分的回调来呼叫客户端......

类似

ServiceHost shintern = new ServiceHost(typeof(InternalService));
shintern.Open();

(后来,我们订阅了客户)......

shintern.GetClients().ForEach(...client_function());

Actualy我有2个服务(Extern Rest / WS,Intern netTcp)正在运行,我想实现类似的东西:

    ServiceExtern::GetSomethingFromInternClients()
    {
         //return values of clients connected to intern Service. 
    }

如果您愿意,我也可以添加一些代码。 问候

1 个答案:

答案 0 :(得分:2)

好吧,我以某种方式做到了(不喜欢它)。

“实习生”客户端所服务的服务看起来像这样。

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single)]
    public class pwGateInternalService : IpwGateInternalService
    {
        static List<SchoolCallback> m_schools = new List<SchoolCallback>();

        //non contract Functions:

        public List<SchoolCallback> GetClientList()
        {
            return m_schools;
        }

        //Contract Functions:

        public ServiceStatus Connect(string schoolname)
        {
            ServiceStatus result = new ServiceStatus();
            int schoolid = Config.GetIdentifier(schoolname);

            //add to dynamic list of schools
            IpwGateInternalCallback callback = OperationContext.Current.GetCallbackChannel<IpwGateInternalCallback>();
            if (m_schools.Find(x => x.callback == callback) == null)
            {
                SchoolCallback school = new SchoolCallback(schoolid, schoolname, callback);
                m_schools.Add(school);

                result.status = eStatus.success;
            }
            else
            {
                //already found
                result.status = eStatus.error;
                result.strError = "a client with your name is already connected";

                //TODO
                //mail?
            }
            return null;
        }

        public void Disconnect()
        { 
            //remove from dynamic list
            IpwGateInternalCallback callback = OperationContext.Current.GetCallbackChannel<IpwGateInternalCallback>();
            SchoolCallback school = m_schools.Find(x => x.callback == callback);
            if (school != null)
            {
                m_schools.Remove(school);
            }


        }//Disconnect()
    }//callback interface

在哪里 - 每当我想访问客户列表时,我都这样做:

pwGateInternalService internService = new pwGateInternalService();
List<SchoolCallback> schools = internService.GetClientList();
SchoolCallback school = schools.Find(x => x.identifier == targetschool.identifier);

if (school != null)
{  
    user = school.callback.GetUser(username);
}