在Silverlight 3 中添加了客户端不同应用程序之间的通信机制,当一台电脑上同时运行多个Silverlight 应用程序的时候,本地消息通讯可以在不同的Silverlight之间创建一个消息通道,有点像是一个Socket链接,一方在监听,一方发送。

发送端

public partial class LM_Sender : UserControl
    {
        //定¨义?本?地?消?息¢发¢送í对?象ó,?这a个?最?关?键ü,?接ó收?方?和í发¢送í方?的?实μ例y名?必?须?一?样ù才?行D,?好?比èMQ的?通¨道à一?样ù
        private LocalMessageSender msgSender = new LocalMessageSender("terryfeng");
        public LM_Sender()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(LM_Sender_Loaded);
        }

        void LM_Sender_Loaded(object sender, RoutedEventArgs e)
        {
            //提á前°加ó载?,?创′建¨消?息¢发¢送í完ê成é的?事?件t处|理í
            msgSender.SendCompleted +=
                new EventHandler<SendCompletedEventArgs>(msgSender_SendCompleted);
        }

        private void btnSent_Click(object sender, RoutedEventArgs e)
        {
            //发¢送í消?息¢
            msgSender.SendAsync(tbInput.Text);
        }

        void msgSender_SendCompleted(object sender, SendCompletedEventArgs e)
        {
            //显?示?回?复′的?消?息¢
            MessageBox.Show(e.Response);
        }
    }

 

接收端

public partial class LM_Rec : UserControl
 {
     public LM_Rec()
     {
         InitializeComponent();
         this.Loaded += new RoutedEventHandler(LM_Rec_Loaded);
     }

     void LM_Rec_Loaded(object sender, RoutedEventArgs e)
     {
         //创′建¨接ó收?消?息¢对?象ó
         LocalMessageReceiver msgRec = new LocalMessageReceiver("terryfeng");
         //创′建¨接ó收?消?息¢的?事?件t处|理í
         msgRec.MessageReceived +=
             new EventHandler<MessageReceivedEventArgs>(msgRec_MessageReceived);
         //开a始?侦ì听y
         msgRec.Listen();
     }

     void msgRec_MessageReceived(object sender, MessageReceivedEventArgs e)
     {
         //显?示?收?到?的?消?息¢
         tbkRec.Text = e.Message;
         //反′馈?消?息¢给?发¢送í者?
         e.Response = "我ò收?到?消?息¢了?,?谢?谢?!?";
     }
 }
posted on 2010-02-17 13:22  冯瑞涛  阅读(527)  评论(0编辑  收藏  举报