Silverlight 3.0 中的 Local Connection
现在很多的需求中需要一个插件实例和另一个实例进行通讯。在同一个页面中调用Html、js等来通讯,而这个往往有一些限制,需要专门的去设置一些权限。在Silverlight 3.0 中新增了一个功能使得跨越实例的通讯变得极为的简单,这个功能为本地连接。
通过本地连接就也可以在不同页面间多个Silverlight实例创建通讯通道。这样就可以创建多个基于Silverlight的应用程序或者基于其他技术的内容在一起的复杂布局。
使用本地连接这里有两个关键的类:
- LocalMessageSender
- LocalMessageReceiver
创建发送器对象,发送消息并且接收响应实现双向通讯。
private void btnSend_Click(object sender, System.Windows.RoutedEventArgs e)
{
LocalMessageSender msgSender = new LocalMessageSender("myReceiver");
msgSender.SendCompleted += new EventHandler(msgSender_SendCompleted);
msgSender.SendAsync(txtMessage.Text);
}
void msgSender_SendCompleted(object sender, SendCompletedEventArgs e)
{
TextBlock tb = new TextBlock();
if (e.Error != null)
{
tb.Text = String.Format("错误: [{0}]", e.Error.Message);
}
else
{
tb.Text = String.Format("{0}", e.Response == null ? "None" : e.Response);
}
spSends.Children.Add(tb);
xScrollViewer.ScrollToVerticalOffset(xScrollViewer.ScrollableHeight);
}
接收{
LocalMessageSender msgSender = new LocalMessageSender("myReceiver");
msgSender.SendCompleted += new EventHandler(msgSender_SendCompleted);
msgSender.SendAsync(txtMessage.Text);
}
void msgSender_SendCompleted(object sender, SendCompletedEventArgs e)
{
TextBlock tb = new TextBlock();
if (e.Error != null)
{
tb.Text = String.Format("错误: [{0}]", e.Error.Message);
}
else
{
tb.Text = String.Format("{0}", e.Response == null ? "None" : e.Response);
}
spSends.Children.Add(tb);
xScrollViewer.ScrollToVerticalOffset(xScrollViewer.ScrollableHeight);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
receiver = new LocalMessageReceiver("myReceiver");
receiver.MessageReceived += new EventHandler(receiver_MessageReceived);
receiver.Listen();
}
void receiver_MessageReceived(object sender, MessageReceivedEventArgs e)
{
e.Response = "发送成功【" + e.Message + "】";
TextBlock tb = new TextBlock();
tb.Text = "接收来自" + e.ReceiverName + "的数据:" + e.Message;
spSends.Children.Add(tb);
xScrollViewer.ScrollToVerticalOffset(xScrollViewer.ScrollableHeight);
}
{
receiver = new LocalMessageReceiver("myReceiver");
receiver.MessageReceived += new EventHandler(receiver_MessageReceived);
receiver.Listen();
}
void receiver_MessageReceived(object sender, MessageReceivedEventArgs e)
{
e.Response = "发送成功【" + e.Message + "】";
TextBlock tb = new TextBlock();
tb.Text = "接收来自" + e.ReceiverName + "的数据:" + e.Message;
spSends.Children.Add(tb);
xScrollViewer.ScrollToVerticalOffset(xScrollViewer.ScrollableHeight);
}
同一页面
实例下载