稳扎稳打Silverlight(54) - 4.0通信之对UDP协议的支持
2010-10-12 12:30:02 来源:WEB开发网UdpAnySourceMulticastClientDemo.xaml.cs
代码
/*
* 用于演示 ASM 的客户端
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
namespace Silverlight40.Communication
{
public partial class UdpAnySourceMulticastClientDemo : Page
{
private UdpAnySourceMulticastChannel _channel;
public UdpAnySourceMulticastClientDemo()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
txtUserName.Text = "匿名" + new Random().Next(1000, 9999).ToString();
_channel = new UdpAnySourceMulticastChannel(IPAddress.Parse("224.0.0.1"), 3006, 2048);
_channel.Opening += new EventHandler(_channel_Opening);
_channel.Received += new EventHandler<UdpPacketEventArgs>(_channel_Received);
_channel.Closing += new EventHandler(_channel_Closing);
Application.Current.Exit += new EventHandler(Current_Exit);
_channel.Open();
}
void _channel_Opening(object sender, EventArgs e)
{
_channel.Send(string.Format("{0}: 进来了 - [{1}]", txtUserName.Text, DateTime.Now.ToString("HH:mm:ss")));
}
void _channel_Received(object sender, UdpPacketEventArgs e)
{
// 因为已经指定了接收信息的缓冲区大小是 2048 ,所以如果信息不够 2048 个字节的的话,空白处均为“\0”
string message = string.Format("{0} - 来自:{1}", e.Message.TrimEnd('\0'), e.Source.ToString());
lstAllMsg.Items.Insert(0, message);
}
void _channel_Closing(object sender, EventArgs e)
{
_channel.Send(string.Format("{0}: 离开了 - [{1}]", txtUserName.Text, DateTime.Now.ToString("HH:mm:ss")));
}
void Current_Exit(object sender, EventArgs e)
{
_channel.Dispose();
}
private void btnSend_Click(object sender, RoutedEventArgs e)
{
SendMsg();
}
private void txtMsg_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
SendMsg();
}
private void SendMsg()
{
_channel.Send(string.Format("{0}: {1} - [{2}]", txtUserName.Text, txtSendMsg.Text, DateTime.Now.ToString("HH:mm:ss")));
txtSendMsg.Text = "";
}
}
}
OK
源码下载:http://files.cnblogs.com/webabcd/Silverlight.rar
Tags:稳扎稳打 Silverlight 通信
编辑录入:爽爽 [复制链接] [打 印]- ››稳扎稳打Silverlight(53) - 4.0通信之对WCF NetTc...
- ››稳扎稳打Silverlight(54) - 4.0通信之对UDP协议的...
- ››稳扎稳打Silverlight(55) - 4.0通信之对UDP协议的...
- ››稳扎稳打Silverlight(56) - 4.0通信之与 WCF Data...
- ››Silverlight for Windows Phone 7开发系列(1):...
- ››Silverlight for Windows Phone 7开发系列(2):...
- ››Silverlight for Windows Phone 7开发系列(3):...
- ››Silverlight for Windows Phone 7开发系列(4):...
- ››Silverlight for Symbian
- ››Silverlight3系列(四)数据绑定 Data Binding 1
- ››稳扎稳打Silverlight 2.0 系列文章索引
- ››稳扎稳打Silverlight(29) - 2.0Tip/Trick之Cookie...
更多精彩
赞助商链接