ICE框架双工通讯+MVVM框架测试案例

准备

 

开发工具 VS2015

ICE框架 https://zeroc.com/

MVVMLight框架

ICE接口文件 

#include "./Identity.ice"
#include "./CommonIPC.ice"

module Demo {
    interface ServerProxy {
        void Register(Ice::Identity ident);
        int GetResultFromServer();
    };

    interface ClientProxy {
        bool SendToClient(string i);
    };
};

预编译指令 (BuildEvent)

echo Setting path for Pre-build event  > iceout.txt
set PATH=$(SolutionDir)3.6.2\;%PATH% >> iceout.txt

echo Calling slice2cs on Printer.ice >> iceout.txt
slice2cs.exe --output-dir $(ProjectDir)ICEGenerated $(ProjectDir)Printer.ice >> iceout.txt 2>&1

第一条是 预编译结果输出,成功失败异常等

第二条是开始预编译(自动生成接口文件相关)

 

 

Server端实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ice;
using System.Collections;
using Demo;

namespace ICETest
{
    public class MyServer : Demo.ServerProxyDisp_
    {
        /// <summary>
        /// 客户端维护
        /// </summary>
        ArrayList _Clients = new ArrayList();
        /// <summary>
        /// 开发给客户端调用的接口,获取随机数
        /// </summary>
        /// <param name="current__"></param>
        /// <returns></returns>
        public override int GetResultFromServer(Current current__)
        {
            var r = new Random();
            Console.WriteLine("客户端获取随机数成功");
            return r.Next(0,100);
        }

        public MyServer()
        {
            Ice.Communicator  _ICEComm = Ice.Util.initialize();
            Ice.Communicator iceComm = Ice.Util.initialize();

            Ice.ObjectAdapter iceAdapter = iceComm.createObjectAdapterWithEndpoints("ServerProxy", "tcp -p " + "10000");
            iceAdapter.add(this, iceComm.stringToIdentity("ServerProxy"));
            iceAdapter.activate();
        }
        /// <summary>
        /// 接收客户端注册,并维护客户端
        /// </summary>
        /// <param name="ident"></param>
        /// <param name="current__"></param>
        public override void Register(Identity ident, Current current__)
        {
            Ice.ObjectPrx @base = current__.con.createProxy(ident);
            ClientProxyPrx client = ClientProxyPrxHelper.uncheckedCast(@base);
            _Clients.Add(client);
            Console.WriteLine("一个新的客户端已经连接");
        }

        /// <summary>
        /// 给客户端发送信息 
        /// </summary>
        /// <param name="s"></param>
        public void SendToClient(string s)
        {
            foreach (var item in _Clients)
            {
                var c = item as ClientProxyPrxHelper;
                c.SendToClient(s);
                Console.WriteLine("发送给客户端:" + s);
            }
        }
    }
}

 

 

Client实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Demo;
using Ice;

namespace MVVMTest
{
    public class MyClient : ClientProxyDisp_
    {

        public event EventHandler Receivedata;
        /// <summary>
        /// 由服务端主动发送过来的数据,通过事件提醒界面更新
        /// </summary>
        /// <param name="i"></param>
        /// <param name="current__"></param>
        /// <returns></returns>
        public override bool SendToClient(string i, Current current__)
        {
            II1 = i;
            if(Receivedata!=null)
            {
                Receivedata(null, null);
            }
            return true;
        }

        public string II1 { get; set; }

        ServerProxyPrx _serverpxy = null;
        Ice.Communicator _ICEComm = null;
        public MyClient()
        {
            _ICEComm = Ice.Util.initialize();
            string connectString = String.Format("ServerProxy:tcp -t {0} -p {1} -h {2}", 100000, 10000, "172.16.35.66");
            ObjectPrx iceProxy = _ICEComm.stringToProxy(connectString);
            _serverpxy = ServerProxyPrxHelper.checkedCast(iceProxy);
        }
        /// <summary>
        /// 由VM层多线程调用,循环执行
        /// </summary>
        /// <returns></returns>
        public  int GetResultFromServer( )
        {
            return _serverpxy.GetResultFromServer();
        }
        /// <summary>
        /// 初次注册自己
        /// </summary>
        public void Register()
        {
            Ice.ObjectAdapter adapter = _ICEComm.createObjectAdapter("");
            Ice.Identity ident = new Identity();
            ident.name =new Guid().ToString();
            ident.category = "";
            adapter.add(this, ident);
            adapter.activate();
            _serverpxy.ice_getConnection().setAdapter(adapter);

            _serverpxy.Register(ident);
        }
    }
}

 

Client ----VM实现

 

using GalaSoft.MvvmLight;
using System.ComponentModel;
using System.Threading;

namespace MVVMTest.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            client = new MyClient();
            client.Receivedata += Client_Receivedata;

            client.Register();
            // Code runs in Blend --> create design time data.
            BackgroundWorker bg = new BackgroundWorker();
            bg.DoWork += Bg_DoWork;
            bg.RunWorkerAsync(); 
        }

        private void Client_Receivedata(object sender, System.EventArgs e)
        {
            RaisePropertyChanged("Test2");
        }

        MyClient client = null;
        private void Bg_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                Test1 = client.GetResultFromServer().ToString();
                RaisePropertyChanged("Test1");
                Thread.Sleep(5000);
            }
        }

        public string Test1
        {
            get; set;
        }

        public string Test2
        {
            get { return client.II1; }
        }
    }
}

Client View实现

 

<Window x:Class="MVVMTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MVVMTest"
        mc:Ignorable="d"
        DataContext="{Binding Main,Source={StaticResource Locator}}"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label x:Name="label1" Content="{Binding Path=Test1, Mode=OneWay}"   HorizontalAlignment="Left" Margin="64,189,0,0" VerticalAlignment="Top" Height="35" Width="222" Background="Yellow"/>
        <Label x:Name="label2" Content="{Binding Path=Test2, Mode=OneWay}"   HorizontalAlignment="Left" Margin="72,114,0,0" VerticalAlignment="Top" Height="35" Width="222" Background="AliceBlue"/>
    </Grid>
</Window>

 

posted on 2017-05-25 10:28  hahanonym  阅读(885)  评论(0编辑  收藏  举报