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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章