WEB开发网
开发学院WEB开发ASP.NET 稳扎稳打Silverlight(54) - 4.0通信之对UDP协议的... 阅读

稳扎稳打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 S

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

上一页  1 2 3 4 

Tags:稳扎稳打 Silverlight 通信

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接