wcf的DuplexChannelFactory演示代码

勇哥注:

全双工方式,如果是从dll调用wcf服务的话,因为无法引用服务以及用app.config配置终结点信息,只能通过硬编码方式来进行。

在网上,DuplexChannelFactory比ChannelFactory更难查到资料。因此在这里放上一些代码,供大家参考。



示例1: RobotClient


 public RobotClient()
 {     // Initilize communication channel
     DuplexChannelFactory = new DuplexChannelFactory<IUiPathRemoteDuplexContract>(new InstanceContext(this), "DefaultDuplexEndpoint");     DuplexChannelFactory.Credentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
     Channel = DuplexChannelFactory.CreateChannel();
 }


示例2: OrationiSlave


        public OrationiSlave()        {
            Binding binding = new NetTcpBinding(SecurityMode.None);
            EndpointAddress defaultEndpointAddress = new EndpointAddress("net.tcp://localhost:57344/Orationi/Master/v1/");
            EndpointAddress discoveredEndpointAddress = DiscoverMaster();
            ContractDescription contractDescription = ContractDescription.GetContract(typeof(IOrationiMasterService));
            ServiceEndpoint serviceEndpoint = new ServiceEndpoint(contractDescription, binding, discoveredEndpointAddress ?? defaultEndpointAddress);            var channelFactory = new DuplexChannelFactory<IOrationiMasterService>(this, serviceEndpoint);            try
            {
                channelFactory.Open();
            }            catch (Exception ex)
            {
                channelFactory?.Abort();
            }            try
            {
                _masterService = channelFactory.CreateChannel();
                _communicationObject = (ICommunicationObject)_masterService;
                _communicationObject.Open();
            }            catch (Exception ex)
            {                if (_communicationObject != null && _communicationObject.State == CommunicationState.Faulted)
                    _communicationObject.Abort();
            }
        }


示例3: submitButton_Click


        private void submitButton_Click(object sender, RoutedEventArgs e)
        {            var login = loginTextBox.Text;            var pass = passwordTextBox.Password;

            Action<String> status = s => {
                statusLabel.Content = s;
                statusLabel.ToolTip = s;
            };            try {
                channelFactory = new DuplexChannelFactory<IService>(new ClientImplementation(_MainWindow), "DnDServiceEndPoint");
                server = channelFactory.CreateChannel();                if (server.Login(login, pass)) {
                    _MainWindow.InitializeServer(channelFactory, server);                    this.DialogResult = true;
                } else {
                    statusLabel.Content = "Login lub hasło nie są poprawne!";                    return;
                }

            } catch (Exception ex) {
                statusLabel.Content = "Nastąpił błąd! Spróbuj ponownie";
                System.IO.StreamWriter file = new System.IO.StreamWriter("log.txt");
                file.WriteLine(ex.ToString());
                file.Close();                return;
            }            this.Close();
        }



示例4: MainWindow


        public MainWindow()
        {
            InitializeComponent();

            EndpointAddress endpointAddress = new EndpointAddress("http://localhost:31337/BesiegedServer/BesiegedMessage");            DuplexChannelFactory<IBesiegedServer> duplexChannelFactory = new DuplexChannelFactory<IBesiegedServer>(m_Client, new WSDualHttpBinding(), endpointAddress);
            m_BesiegedServer = duplexChannelFactory.CreateChannel();            // Subscribe in a separate thread to preserve the UI thread
            Task.Factory.StartNew(() =>
            {
                CommandConnect commandConnect = new CommandConnect();
                m_BesiegedServer.SendMessage(commandConnect.ToXml());
            });

            Task.Factory.StartNew(() =>
            {                while (true)
                {
                    Command command = m_Client.MessageQueue.Take();
                    ProcessMessage(command);
                }
            }, TaskCreationOptions.LongRunning);

            GameLobbyCollection = new ObservableCollection<CommandNotifyGame>();
            DataContext = this;
        }


示例5: RegisterViewModel


 public RegisterViewModel() {     var channelFactory = new DuplexChannelFactory<IChattingService>(new ClientService(), "ChattingServiceEndPoint");
     _server = channelFactory.CreateChannel();
     Register = new RelayCommand(OnRegister, () => !(string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)));
     ClearCommand = new RelayCommand(OnClear);
 }


示例6: ConnectIpc


        public static void ConnectIpc(IServiceRemotingCallback serviceRemotingCallback)
        {
            InstanceContext instanceContext = new InstanceContext(serviceRemotingCallback);

            PipeFactory = new DuplexChannelFactory<IServiceRemoting>(instanceContext, new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/BitCollectors.PlinkService/PlinkService"));
            RemotingObject = PipeFactory.CreateChannel();
        }


示例7: MonitorForm_Load


        //其他成员
        private void MonitorForm_Load(object sender, EventArgs e)        {            string header = string.Format("{0, -13}{1, -22}{2}", "Client", "Time", "Event");            this.listBoxExecutionProgress.Items.Add(header);
            _syncContext = SynchronizationContext.Current;
            _callbackInstance = new InstanceContext(new CalculatorCallbackService());
            _channelFactory = new DuplexChannelFactory<ICalculator>(_callbackInstance, "calculatorservice");

            EventMonitor.MonitoringNotificationSended += ReceiveMonitoringNotification;            this.Disposed += delegate
            {
            EventMonitor.MonitoringNotificationSended -= ReceiveMonitoringNotification;
            _channelFactory.Close();
            };            for (int i = 0; i < 2; i++)
            {
            ThreadPool.QueueUserWorkItem(state =>
            {                int clientId = Interlocked.Increment(ref _clientId);
                EventMonitor.Send(clientId, EventType.StartCall);
                ICalculator proxy = _channelFactory.CreateChannel();                using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel))
                {
                    MessageHeader<int> messageHeader = new MessageHeader<int>(clientId);
                    OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader.GetUntypedHeader(EventMonitor.CientIdHeaderLocalName, EventMonitor.CientIdHeaderNamespace));
                    proxy.Add(1, 2);
                }
                EventMonitor.Send(clientId, EventType.EndCall);
            }, null);
            }
        }

示例8: Connect


        /// <summary>
        /// Connect to game server
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public bool Connect(String IP)        {            // Create a pipeFactory
            DuplexChannelFactory<IMessage> pipeFactory =                  new DuplexChannelFactory<IMessage>(                      new InstanceContext(this),                      new NetTcpBinding(),                //new EndpointAddress(String.Format("net.tcp://{0}:8000/GameServer", IP)));
                      new EndpointAddress(String.Format("net.tcp://{0}:8000/GameServer", "localhost")));            try
            {                // Creating the communication channel
                pipeProxy = pipeFactory.CreateChannel();                // register for events 
                pipeProxy.Subscribe();                // join the game 
                myID = pipeProxy.join(me.Username, me.money, me.numOfGames, me.ID);                if (pipeProxy.runningGame())
                {
                    pipeProxy.resetGame();
                }                return true;
            }            catch (Exception e)
            {                
                return false;
            }
        }


示例9: Test


        public static void Test()        {            string baseAddress = "net.tcp://" + Environment.MachineName + ":8000/Service";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            host.AddServiceEndpoint(typeof(ITest), new NetTcpBinding(SecurityMode.None), "");
            host.Open();
            Console.WriteLine("Host opened");

            AutoResetEvent evt = new AutoResetEvent(false);
            MyCallback callback = new MyCallback(evt);            DuplexChannelFactory<ITest> factory = new DuplexChannelFactory<ITest>(                new InstanceContext(callback),                new NetTcpBinding(SecurityMode.None),                new EndpointAddress(baseAddress));
            ITest proxy = factory.CreateChannel();

            Console.WriteLine(proxy.Hello("foo bar"));
            evt.WaitOne();

            ((IClientChannel)proxy).Close();
            factory.Close();

            Console.Write("Press ENTER to close the host");
            Console.ReadLine();
            host.Close();
        }


示例10: MainWindow


        public MainWindow()
        {            try
            {                //Center the window on startup
                WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                InitializeComponent();
                createGrid();                // Configure the Endpoint details
                DuplexChannelFactory<ITileBag> channel = new DuplexChannelFactory<ITileBag>(this, "TileBag");                // Activate a remote Bag object
                bag = channel.CreateChannel();                // Register this client for the callback service
                bag.RegisterForCallbacks();

                lblPlayerScore.Content = 0;
                pWin = new PlayerLobby(this, bag.ClientCount);
                pWin.Show();                this.Hide();
            }            catch (Exception ex)
            {
                MessageBox.Show("Error Initializing Window " + ex.Message);
            }
        }


示例11: Main


        static void Main(string[] args)        {            var fact = new ChannelFactory<IDeviceManagerService>("deviceEndpoint");

            InstanceContext callback = new InstanceContext(new ServiceCallback());            var dup = new DuplexChannelFactory<ICardReaderEventsSubscribe>(callback, "dupSocket");            var cardReaderSub = dup.CreateChannel();            var cha = fact.CreateChannel();            using (fact)
            {                var devices = cha.GetAllDevices();                //cha.Open(new  devices[0].FullSerialNumber );

            }
            Console.WriteLine("try a new");
            Console.ReadKey();

            Console.WriteLine("REading duplex");

            cardReaderSub.SubscribeToCardSwipeByhost("Local");

            Console.ReadKey();            var fact1 = new ChannelFactory<IDeviceManagerService>("deviceEndpoint");            var cha1 = fact1.CreateChannel();            using (fact1)
            {                var devices = cha1.GetAllDevices();
            }
        }


示例12: StartP2PClient


        private  void StartP2PClient( )
        {            string s = ConfigurationManager.AppSettings["IsSupportGroup"];            if (s.Equals("no", StringComparison.OrdinalIgnoreCase))
            {                return;
            }
            InstanceContext context = new InstanceContext(new P2PChatService());            DuplexChannelFactory<IP2PChatService> factory = new DuplexChannelFactory<IP2PChatService>(context,"p2p", new EndpointAddress("net.p2p://" + groupId));


            channel = factory.CreateChannel();
            clients.Add(groupId, this);           

           
            new Thread(new ThreadStart(() =>
            {                try
                {
                    channel.Join();
                }                catch (Exception ex)
                {
                    MyLogger.Logger.Error("进入群组聊天室时出错",ex);
                }
            })).Start();
           
        }


示例13: ClientViewModel


 public ClientViewModel() {     var channelFactory = new DuplexChannelFactory<IChattingService>(new ClientService(), "ChattingServiceEndPoint");
     _server = channelFactory.CreateChannel();
     This = this;
     CreateCommands();
 }


示例14: TestOneWayCallbackConcurencyOnNamedPipe


        public void TestOneWayCallbackConcurencyOnNamedPipe()        {            var address = @"net.pipe://127.0.0.1/testpipename" + MethodBase.GetCurrentMethod().Name;            var srv = new CallbackService();            var callback = new CallbackServiceCallback();            using (var server = new ServiceHost(srv, new Uri(address)))
            {
                server.AddServiceEndpoint(typeof(ICallbackService), new NetNamedPipeBinding { }, address);
                server.Open();                using (var channelFactory = new DuplexChannelFactory<ICallbackService>(new InstanceContext(callback), new NetNamedPipeBinding { }))
                {                    var client = channelFactory.CreateChannel(new EndpointAddress(address));                    for (int i = 0; i < 20; i++)
                        client.OneWayExecute();                    while (callback.Count != 20)
                    {
                        Thread.Sleep(10);
                    }

                }
            }
        }


示例15: NetTcpBinding_DuplexCallback_ReturnsXmlComplexType


    public static void NetTcpBinding_DuplexCallback_ReturnsXmlComplexType()
    {        DuplexChannelFactory<IWcfDuplexService_Xml> factory = null;
        NetTcpBinding binding = null;
        WcfDuplexServiceCallback callbackService = null;
        InstanceContext context = null;
        IWcfDuplexService_Xml serviceProxy = null;
        Guid guid = Guid.NewGuid();        try
        {
            binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;

            callbackService = new WcfDuplexServiceCallback();
            context = new InstanceContext(callbackService);

            factory = new DuplexChannelFactory<IWcfDuplexService_Xml>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_XmlDuplexCallback_Address));
            serviceProxy = factory.CreateChannel();

            serviceProxy.Ping_Xml(guid);
            XmlCompositeTypeDuplexCallbackOnly returnedType = callbackService.XmlCallbackGuid;            // validate response
            Assert.True((guid.ToString() == returnedType.StringValue), String.Format("The Guid to string value sent was not the same as what was returned.\nSent: {0}\nReturned: {1}", guid.ToString(), returnedType.StringValue));

            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }        finally
        {
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }


本文出自勇哥的网站《少有人走的路》wwww.skcircle.com,转载请注明出处!讨论可扫码加群:
本帖最后由 勇哥,很想停止 于 2024-04-15 09:06:41 编辑

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

会员中心
搜索
«    2024年4月    »
1234567
891011121314
15161718192021
22232425262728
2930
网站分类
标签列表
最新留言
    热门文章 | 热评文章 | 随机文章
文章归档
友情链接
  • 订阅本站的 RSS 2.0 新闻聚合
  • 扫描加本站机器视觉QQ群,验证答案为:halcon勇哥的机器视觉
  • 点击查阅微信群二维码
  • 扫描加勇哥的非标自动化群,验证答案:C#/C++/VB勇哥的非标自动化群
  • 扫描加站长微信:站长微信:abc496103864
  • 扫描加站长QQ:
  • 扫描赞赏本站:
  • 留言板:

Powered By Z-BlogPHP 1.7.2

Copyright Your skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864