欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

wp wp8:服务器推送

程序员文章站 2022-04-30 10:02:35
...
前提:必须使用真机,真机注册

服务器端使用的是winform做的

客户端wp8系统 nokia920

client代码:

图:



注意一定要在wmappmanifest.xml中勾选 pushnotifiation 图:



上代码:

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using push_client.Resources;
using Microsoft.Phone.Notification;

namespace push_client
{
    public partial class MainPage : PhoneApplicationPage
    {

        // 构造函数 
        public MainPage()
        {
            HttpNotificationChannel myChannel = null;
            // 推送信道的名字,随便取一个就行了 
            string ChannelName = "ToastChannel";
            InitializeComponent();
            // Find静态方法可以根据名字查找信道 
            myChannel = HttpNotificationChannel.Find(ChannelName);
            // 如果找不到,就要创建一个了 
            if (myChannel == null)
            {
                myChannel = new HttpNotificationChannel(ChannelName);
                // 注册事件 
                myChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(myChannel_ChannelUriUpdated);
                myChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(myChannel_ErrorOccurred);
                myChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(myChannel_ShellToastNotificationReceived);
                // 打开信道 
                myChannel.Open();
                // 绑定Toast通知,这样在程序不在前台时才会显示 
                // 屏幕上方的通知提示条 
                myChannel.BindToShellToast();
            }
            else
            {
                // 如果存在,还要注册一次事件,因为在程序被扔到后台后可能会删除事件绑定 
                myChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(myChannel_ChannelUriUpdated);
                myChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(myChannel_ErrorOccurred);
                myChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(myChannel_ShellToastNotificationReceived);

                // 在“输出”窗输出URL,因为我们只是测试,这样一来方便一点 
                System.Diagnostics.Debug.WriteLine("通道URI为:{0}", myChannel.ChannelUri.ToString());
            }
        }

        void myChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
        {
            string msg = "";
            foreach (string key in e.Collection.Keys)
            {
                msg += key + " : " + e.Collection[key] + "\r\n";
            }
            Dispatcher.BeginInvoke(() =>
            {
                //this.txtInfo.Text = msg;
                System.Diagnostics.Debug.WriteLine(msg);
            });
        }

        void myChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
        {
            //Dispatcher.BeginInvoke(() => MessageBox.Show(e.Message));
            System.Diagnostics.Debug.WriteLine(e.Message);
        }

        void myChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {
            // 当URL发生改变后,还要输出一次 
            // 保证我们得到的是最新版本的URI 
            Dispatcher.BeginInvoke(() =>
            {

                //服务器端要用到的uri
                System.Diagnostics.Debug.WriteLine("通道URI:{0}", e.ChannelUri.ToString());
            });
        }

        // 这个方法不用我多介绍了 
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (NavigationContext.QueryString.ContainsKey("toastmsg"))
            {
                //this.txtInfo.Text = NavigationContext.QueryString["toastmsg"];
            }
        } 
       
    }
}



ReceiveMessagePage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace push_client
{
    public partial class ReceiveMessagePage : PhoneApplicationPage
    {
        public ReceiveMessagePage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

            try
            {
                string t1String = "";

                if (NavigationContext.QueryString.TryGetValue("tp1", out t1String))
                {
                    t1.Text = t1String;

                }

                string t2String = "";

                if (NavigationContext.QueryString.TryGetValue("tp2", out t2String))
                {
                    t2.Text = t2String;

                }
            }
            catch (Exception)
            {

            }

        }

    } 
}

服务器端代码:

图:



上代码:

Form1.Designer.cs

using System;
using System.Windows.Forms;
namespace push_service
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码


        TextBox txtResult;

        TextBox txtValue1;
        TextBox txtValue2;

        private void InitializeComponent()
        {
            this.SuspendLayout();
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.Width = 800;

            Button button = new Button();
            button.Width = 80;
            button.Height = 30;
            button.Left = 340;
            button.Top = 30;
            button.Text = "执   行";
            button.Click += new EventHandler(btnSend_Click);
            this.Controls.Add(button);

            txtValue1 = new TextBox();
            txtValue1.Text = "显示在toast中的参数1";
            txtValue1.Left = 10;
            txtValue1.Top = 10;
            txtValue1.Width = 300;
            txtValue1.Height = 50;
            this.Controls.Add(txtValue1);

            txtValue2 = new TextBox();
            txtValue2.Text = "显示在toast中的参数2";
            txtValue2.Left = 10;
            txtValue2.Top = 60;
            txtValue2.Width = 300;
            txtValue2.Height = 50;
            this.Controls.Add(txtValue2);

            txtResult = new TextBox();
            txtResult.Left = 10;
            txtResult.Top = 120;
            txtResult.Width = 300;
            txtResult.Height = 50;
            this.Controls.Add(txtResult);

        }

        #endregion
    }
}

Form1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace push_service
{
    public partial class Form1 : Form
    {

      

        public Form1()
        {
            InitializeComponent();

        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            //uri是客户端 在注册之后 运行在真机上得到的uri
            string URI = "http://db3.notify.live.net/throttledthirdparty/*************************";
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URI);
            myRequest.ContentType = "text/xml";
            myRequest.Headers.Add("X-WindowsPhone-Target", "toast");
          
            /*
             *   X-NotificationClass 处理间隔
             *   2 - 立即发送
             *   12 - 450秒内发送
             *   22 - 900秒内发送
             */
            myRequest.Headers.Add("X-NotificationClass", "2");

            // 要发送的内容 
            //注意:Param中&要转义为&amp;
            string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
            "<wp:Notification xmlns:wp=\"WPNotification\">" +
                "<wp:Toast>" +
                    "<wp:Text1>" + txtValue1.Text + "</wp:Text1>" +
                    "<wp:Text2>" + txtValue2.Text + "</wp:Text2>" +
                    "<wp:Param>" + "/ReceiveMessagePage.xaml?tp1=" + "11" + "&amp;tp2=" + "22"
                  + "</wp:Param>" +
                "</wp:Toast>" +
            "</wp:Notification>";

            byte[] buffer = Encoding.UTF8.GetBytes(toastMessage);
            myRequest.ContentLength = buffer.Length;
            myRequest.Method = "POST";

            using (System.IO.Stream stream = myRequest.GetRequestStream())
            {
                stream.Write(buffer, 0, buffer.Length);
            }

            // 接收回应 
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

            string headers = "";
            foreach (var hd in myResponse.Headers.AllKeys)
            {
                headers += hd + " : " + myResponse.Headers[hd] + " | ";
            }
            headers += "\r\n";
            string msg = "";
            using (System.IO.Stream recStream = myResponse.GetResponseStream())
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(recStream, Encoding.UTF8);
                msg = reader.ReadToEnd();
                reader.Close();
            }
            msg += "\r\n\r\n";
            txtResult.AppendText(headers + msg);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        } 
    }
}

服务器端运行效果:



客户端接受效果:

相关标签: wp