Windows Phone开发(46):与Socket有个约会

移动开发
在很多情况下,关于Socket的例子,都会做一个聊天程序的,不过,聊天程序要求服务器端和客户都具有发送和接收数据的功能,这样会增加实例的难度和代码长度,不方便入门者阅读。所以,想了一下,今天咱们不玩聊天的,今天咱们玩遥控飞机,如何?

不知道大家有没有“谈Socket色变”的经历?就像我一位朋友所说的,Socket这家伙啊,不得已而用之。哈,Socket真的那么恐怖吗?

其实这话一点也不假,Socket有时候真的不太好操控,也不好维护,但不管怎么样,我们还是要面对它的,没准Socket是一位大美女哦。

关于Socket的前世今生就不用我详述了,关于她的历史,已经不少人仁志士为她立传 写著了,像我们国内的百度百科、互动百科等;全球著名的如维基百科之属。而且,能加入WP开发的学习行列的,我想各位对.NET的其它技术肯定是有一定基 础的。我也相信,各位同仁过去一定也写过与Socket打交道的程序。那么,WP中的Socket又将如何呢?

前提公布答案吧,在WP中使用Socket跟你在其它桌面应用项目如WinForm,WPF等中是一样的,而且说白了,WP中的Socket只不过是从Silverlight框架中继承过来的。

.NET的一大优势就是集成性和统一性都好,这不,你看,无论你是编写桌面应用程序,还是WP上的应用程序,你会发现,你的学习成本不高,很多东西都是一样的,而且是相通的。显然这也是Win8和WP8的应用程序可以整合的原因吧。

在WP中使用Socket要注意以下几点:

1、WP客户端应用程序一般不被视为服务器端,因为不能进行绑定本地终结点和监听连接。但是,收发数据是没问题D。

2、在WP中的Socket操作(连接、接收以及发送)都是异步进行的。如果希望UI线程和后前线程进行同步,不妨使用System.Threading.ManualResetEvent类,这个东西不好讲述,也不好理解。这样吧,我举一个例子。

有一天,NC和脑残因为一件小事闹冲突,闹来闹去还是不能解决,怎么办呢?于是,NC和脑残决定来一场比试。两人约定以跑步方式比试,谁跑得快谁就是胜利者。然而,NC这个人一向比较自负,他相信脑残绝对跑不过他。这样,NC就修改了比赛规则:

NC让脑残先跑5秒,然后他才开始。

假设NC是主线程,脑残是后台线程,现在的情况是:主线程先等待一会儿,让后台线程先 执行;后台线程执行5秒后向主线程发出信号,主线程收到信号后再继续往下执行。按照故事里的情节:NC先让脑残跑5秒钟,他自己就在起跑线上等待,脑残跑 了5秒后向NC发出信号,NC看到信号后就开始跑。

下面介绍一个类——SocketAsyncEventArgs。

这个类作为启动异步操作时传递的参数,它可以包含如接收数据的缓冲区、远程主机、用户自定义对象等内容,这个类并不复杂,打开“对象浏览器”看看就一目了然了。

要设置用于异步接收数据的缓冲区,应调用SetBuffer方法。

好,理论就扯到这儿,其实也没有什么新的知识点,我只是简单提一下罢了。

按照惯例,大家都会猜到,理论过后要干什么了,是的,付诸实践。

在很多情况下,关于Socket的例子,都会做一个聊天程序的,不过,聊天程序要求服务器端和客户都具有发送和接收数据的功能,这样会增加实例的难度和代码长度,不方便入门者阅读。所以,想了一下,今天咱们不玩聊天的,今天咱们玩遥控飞机,如何?

程序代码较长,也不便于逐一来讲解,这样吧,为了保持代码的可读性,我会把完整的代码都贴出来,在代码中我会适当地加上注释。

先说一下原理,利用Socket进行通讯这不用说了,那是肯定的。功能是通过WP手机客户端应用程序来控制PC端播放、暂停和停止动画,而动画嘛,也不弄那么复杂了,就弄个矩形从左边移到右边的动画吧。

***部分  服务器端

既然要播放动画,少不了要用WPF了,而且,也方便贴界面布局的代码。

1、新建WPF应用程序项目。

2、打开MainWindow.xaml文件(默认新建项目后自动打开),输入以下XAML代码。

  1. <Window x:Class="MYServer.MainWindow"   
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  4.         Title="服务器端" Height="350" Width="525">   
  5.     <Window.Resources>   
  6.         <Storyboard x:Key="std">   
  7.             <DoubleAnimation Duration="0:0:5"   
  8.                                  Storyboard.TargetName="rect"   
  9.                                  Storyboard.TargetProperty="(Rectangle.RenderTransform).(TranslateTransform.X)"   
  10.                                  To="400"/>   
  11.         </Storyboard>   
  12.     </Window.Resources>   
  13.     <Grid>   
  14.         <Grid.RowDefinitions>   
  15.             <RowDefinition />   
  16.             <RowDefinition Height="Auto" />   
  17.         </Grid.RowDefinitions>   
  18.         <Rectangle x:Name="rect" Grid.Row="0" Width="50" Height="50" Fill="Orange" HorizontalAlignment="Left" VerticalAlignment="Center">   
  19.             <Rectangle.RenderTransform>   
  20.                 <TranslateTransform X="0" Y="0"/>   
  21.             </Rectangle.RenderTransform>   
  22.         </Rectangle>   
  23.         <TextBlock Name="txtDisplay" Grid.Row="1"/>   
  24.     </Grid>   
  25. </Window>   

3、打开MainWindow.xaml.cs文件,完成后台代码逻辑。

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Text;   
  5. using System.Windows;   
  6. using System.Windows.Controls;   
  7. using System.Windows.Data;   
  8. using System.Windows.Documents;   
  9. using System.Windows.Input;   
  10. using System.Windows.Media;   
  11. using System.Windows.Media.Imaging;   
  12. using System.Windows.Navigation;   
  13. using System.Windows.Shapes;   
  14. using System.Windows.Media.Animation;   
  15. using System.IO;   
  16. using System.Net;   
  17. using System.Net.Sockets;   
  18. namespace MYServer   
  19. {   
  20.     /// <summary>   
  21.     /// MainWindow.xaml 的交互逻辑   
  22.     /// </summary>   
  23.     public partial class MainWindow : Window   
  24.     {   
  25.         Storyboard std = null//演示图板   
  26.         public MainWindow()   
  27.         {   
  28.             InitializeComponent();   
  29.             // 从资源中把Key为std的Storyboard读出来   
  30.             std = this.Resources["std"as Storyboard;   
  31.             // 声明用于监听连接请求的Socket   
  32.             Socket Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);   
  33.             IPEndPoint local = new IPEndPoint(IPAddress.Any, 1377); //监听所有网络接口上的地址   
  34.             Server.Bind(local);// 绑定本地终结点   
  35.             Server.Listen(100);// 侦听连接请求   
  36.             // 开始异步接受传入的连接请求   
  37.             Server.BeginAccept(new AsyncCallback(this.AcceptSocketCallback), Server);   
  38.         }   
  39.         /// <summary>   
  40.         /// 接受传入的Socket的回调   
  41.         /// </summary>   
  42.         private void AcceptSocketCallback(IAsyncResult ia)   
  43.         {   
  44.             Socket _socket = ia.AsyncState as Socket;   
  45.             Socket accptSocket = _socket.EndAccept(ia);   
  46.             try   
  47.             {   
  48.                 IPEndPoint remote = (IPEndPoint)accptSocket.RemoteEndPoint;   
  49.                 // 显示客户端的IP   
  50.                 Dispatcher.BeginInvoke(new Action<string>(this.SetIPForText), remote.Address.ToString());   
  51.                 StateObject so = new StateObject();   
  52.                 so.theSocket = accptSocket;   
  53.                 // 开始异步接收消息   
  54.                 accptSocket.BeginReceive(so.Buffer, 0, so.Buffer.Length, SocketFlags.None, new AsyncCallback(this.ReceiveCallback), so);   
  55.             }   
  56.             catch   
  57.             {   
  58.             }   
  59.             // 继续接受连接请求   
  60.             _socket.BeginAccept(new AsyncCallback(this.AcceptSocketCallback), _socket);   
  61.         }   
  62.         /// <summary>   
  63.         /// 接收消息的回调   
  64.         /// </summary>   
  65.         private void ReceiveCallback(IAsyncResult ia)   
  66.         {   
  67.             StateObject _so = ia.AsyncState as StateObject;   
  68.             Socket _socket = _so.theSocket;   
  69.             try   
  70.             {   
  71.                 int n = _socket.EndReceive(ia);//n就是接收到的字节数   
  72.                 string msg = Encoding.UTF8.GetString(_so.Buffer, 0, n);   
  73.                 // 判断客户端发送了啥命令   
  74.                 switch (msg)   
  75.                 {   
  76.                     case "play":   
  77.                         Dispatcher.BeginInvoke(new Action(this.Play), null);   
  78.                         break;   
  79.                     case "pause":   
  80.                         Dispatcher.BeginInvoke(new Action(this.Pause), null);   
  81.                         break;   
  82.                     case "stop":   
  83.                         Dispatcher.BeginInvoke(new Action(this.Stop), null);   
  84.                         break;   
  85.                     default:   
  86.                         break;   
  87.                 }   
  88.             }   
  89.             catch    
  90.             {   
  91.             }   
  92.             _so = new StateObject();   
  93.             _so.theSocket = _socket;   
  94.             // 继续接收消息   
  95.             _socket.BeginReceive(_so.Buffer,   
  96.                                 0,   
  97.                                 _so.Buffer.Length,   
  98.                                 SocketFlags.None,   
  99.                                 new AsyncCallback(this.ReceiveCallback),   
  100.                                 _so);   
  101.         }   
  102.         /// <summary>   
  103.         /// 显示客户端的IP   
  104.         /// </summary>   
  105.         private void SetIPForText(string ip)   
  106.         {   
  107.             this.txtDisplay.Text = "客户端IP:" + ip;   
  108.         }   
  109.         #region 控制动画的方法   
  110.         private void Play()   
  111.         {   
  112.             std.Begin();   
  113.         }   
  114.         private void Pause()   
  115.         {   
  116.             std.Pause();   
  117.         }   
  118.         private void Stop()   
  119.         {   
  120.             std.Stop();   
  121.         }   
  122.         #endregion   
  123.     }   
  124.     /// <summary>   
  125.     /// 用于异步Socket操作传递的状态对象   
  126.     /// </summary>   
  127.     public class StateObject   
  128.     {   
  129.         private const int BUFFER_SIZE = 512;   
  130.         public byte[] Buffer { get;  set; }   
  131.         public Socket theSocket { getset; }   
  132.         /// <summary>   
  133.         /// 构造函数   
  134.         /// </summary>   
  135.         public StateObject()   
  136.         {   
  137.             this.Buffer = new byte[BUFFER_SIZE];   
  138.         }   
  139.     }   
  140. }   

别走开,下页为您介绍WP客户端

 #p#

第二部分  WP客户端

1、新建Windows Phone应用程序项目。

2、打开MainPage.xaml文件,参考下面的XAML代码。

  1. <phone:PhoneApplicationPage    
  2.     x:Class="WPClient.MainPage"   
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  5.     xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"   
  6.     xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"   
  7.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   
  8.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"   
  9.     mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"   
  10.     FontFamily="{StaticResource PhoneFontFamilyNormal}"   
  11.     FontSize="{StaticResource PhoneFontSizeNormal}"   
  12.     Foreground="{StaticResource PhoneForegroundBrush}"   
  13.     SupportedOrientations="Portrait" Orientation="Portrait"   
  14.     shell:SystemTray.IsVisible="True">   
  15.     <!--LayoutRoot 是包含所有页面内容的根网格-->   
  16.     <Grid x:Name="LayoutRoot" Background="Transparent">   
  17.         <Grid.RowDefinitions>   
  18.             <RowDefinition Height="Auto"/>   
  19.             <RowDefinition Height="*"/>   
  20.         </Grid.RowDefinitions>   
  21.         <!--TitlePanel 包含应用程序的名称和页标题-->   
  22.         <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">   
  23.             <TextBlock x:Name="ApplicationTitle" Text="我的应用程序" Style="{StaticResource PhoneTextNormalStyle}"/>   
  24.             <TextBlock x:Name="PageTitle" Text="页面名称" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>   
  25.         </StackPanel>   
  26.         <!--ContentPanel - 在此处放置其他内容-->   
  27.         <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">   
  28.             <Grid.RowDefinitions>   
  29.                 <RowDefinition Height="auto"/>   
  30.                 <RowDefinition Height="*"/>   
  31.             </Grid.RowDefinitions>   
  32.             <Grid Grid.Row="0">   
  33.                 <Grid.ColumnDefinitions>   
  34.                     <ColumnDefinition Width="Auto" />   
  35.                     <ColumnDefinition />   
  36.                     <ColumnDefinition Width="Auto" />   
  37.                 </Grid.ColumnDefinitions>   
  38.                 <TextBlock Grid.Column="0" VerticalAlignment="Center" Text="服务器IP:" />   
  39.                 <TextBox Name="txtServerIP" Grid.Column="1"/>   
  40.                 <Button Grid.Column="2" Content="连接" Click="onConnect"/>   
  41.             </Grid>   
  42.             <StackPanel Grid.Row="1">   
  43.                 <Button Content="放播动画" Click="onPlay"/>   
  44.                 <Button Content="暂停动画" Click="onPause"/>   
  45.                 <Button Content="停止动画" Click="onStop"/>   
  46.                 <TextBlock Name="txtbInfo" Margin="3,18,3,0"/>   
  47.             </StackPanel>   
  48.         </Grid>   
  49.     </Grid>   
  50.     <!--演示 ApplicationBar 用法的示例代码-->   
  51.     <!--<phone:PhoneApplicationPage.ApplicationBar>   
  52.         <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">   
  53.             <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="按钮 1"/>   
  54.             <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="按钮 2"/>   
  55.             <shell:ApplicationBar.MenuItems>   
  56.                 <shell:ApplicationBarMenuItem Text="菜单项 1"/>   
  57.                 <shell:ApplicationBarMenuItem Text="菜单项 2"/>   
  58.             </shell:ApplicationBar.MenuItems>   
  59.         </shell:ApplicationBar>   
  60.     </phone:PhoneApplicationPage.ApplicationBar>-->   
  61. </phone:PhoneApplicationPage>   

3、打开MainPage.xaml.cs,输入以下代码。

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Net;   
  5. using System.Windows;   
  6. using System.Windows.Controls;   
  7. using System.Windows.Documents;   
  8. using System.Windows.Input;   
  9. using System.Windows.Media;   
  10. using System.Windows.Media.Animation;   
  11. using System.Windows.Shapes;   
  12. using Microsoft.Phone.Controls;   
  13. using System.Net.Sockets;   
  14. using System.IO;   
  15. using System.Threading;   
  16. namespace WPClient   
  17. {   
  18.     public partial class MainPage : PhoneApplicationPage   
  19.     {   
  20.         Socket mySocket = null;   
  21.         ManualResetEvent MyEvent = null;   
  22.         // 构造函数   
  23.         public MainPage()   
  24.         {   
  25.             InitializeComponent();   
  26.         }   
  27.         protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)   
  28.         {   
  29.             base.OnNavigatedTo(e);   
  30.             if (mySocket == null)   
  31.             {   
  32.                 mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);   
  33.             }   
  34.             if (MyEvent == null)   
  35.             {   
  36.                 MyEvent = new ManualResetEvent(false);   
  37.             }   
  38.         }   
  39.         protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)   
  40.         {   
  41.             if (mySocket != null)   
  42.             {   
  43.                 mySocket.Shutdown(SocketShutdown.Both);   
  44.                 mySocket.Close();   
  45.             }   
  46.             base.OnNavigatedFrom(e);   
  47.         }   
  48.         private void onConnect(object sender, RoutedEventArgs e)   
  49.         {   
  50.             if (mySocket != null)   
  51.             {   
  52.                 SocketAsyncEventArgs connArg = new SocketAsyncEventArgs();   
  53.                 // 要连接的远程服务器   
  54.                 connArg.RemoteEndPoint = new DnsEndPoint(this.txtServerIP.Text, 1377);   
  55.                 // 操作完成后的回调   
  56.                 connArg.Completed += (sendObj, arg) =>   
  57.                 {   
  58.                     if (arg.SocketError == SocketError.Success) //连接成功   
  59.                     {   
  60.                         Dispatcher.BeginInvoke(() => txtbInfo.Text = "连接成功。");   
  61.                     }   
  62.                     else   
  63.                     {   
  64.                         Dispatcher.BeginInvoke(() =>   
  65.                         {   
  66.                             txtbInfo.Text = "连接失败,错误:" + arg.SocketError.ToString();   
  67.                         });   
  68.                     }   
  69.                     // 向调用线程报告操作结束   
  70.                     MyEvent.Set();   
  71.                 };   
  72.                 // 重置线程等待事件   
  73.                 MyEvent.Reset();   
  74.                 txtbInfo.Text = "正在连接,请等候……";   
  75.                 // 开始异连接   
  76.                 mySocket.ConnectAsync(connArg);   
  77.                 // 等待连接完成   
  78.                 MyEvent.WaitOne(6000);   
  79.             }   
  80.         }   
  81.         private void onPause(object sender, RoutedEventArgs e)   
  82.         {   
  83.             SendCommand("pause");   
  84.         }   
  85.         private void onStop(object sender, RoutedEventArgs e)   
  86.         {   
  87.             SendCommand("stop");   
  88.         }   
  89.         private void onPlay(object sender, RoutedEventArgs e)   
  90.         {   
  91.             SendCommand("play");   
  92.         }   
  93.         private void SendCommand(string txt)   
  94.         {   
  95.             if (mySocket != null && mySocket.Connected)   
  96.             {   
  97.                 SocketAsyncEventArgs sendArg = new SocketAsyncEventArgs();   
  98.                 byte[] buffer = System.Text.Encoding.UTF8.GetBytes(txt);   
  99.                 sendArg.SetBuffer(buffer, 0, buffer.Length);   
  100.                 // 发送完成后的回调   
  101.                 sendArg.Completed += (objSender, mArg) =>   
  102.                     {   
  103.                         // 如果操作成功   
  104.                         if (mArg.SocketError == SocketError.Success)   
  105.                         {   
  106.                             Dispatcher.BeginInvoke(() => txtbInfo.Text = "发送成功。");   
  107.                         }   
  108.                         else   
  109.                         {   
  110.                             Dispatcher.BeginInvoke(() =>   
  111.                                 {   
  112.                                     this.txtbInfo.Text = "发送失败,错误:" + mArg.SocketError.ToString();   
  113.                                 });   
  114.                         }   
  115.                         // 报告异步操作结束   
  116.                         MyEvent.Set();   
  117.                     };   
  118.                 // 重置信号   
  119.                 MyEvent.Reset();   
  120.                 txtbInfo.Text = "正在发送,请等候……";   
  121.                 // 异步发送   
  122.                 mySocket.SendAsync(sendArg);   
  123.                 // 等待操作完成   
  124.                 MyEvent.WaitOne(6000);   
  125.             }   
  126.         }   
  127.     }   
  128. }   

先运行服务器端,再在WP模拟器或真实手机上运行客户端。

在手机客户端中,输入IP地址,点“连接”,连接成功后,就可以发送指令了。

 好的,就到这儿吧,示例的源码我会上专到“资源”中,有需要的话,大家可以按标题下载。

责任编辑:闫佳明 来源: oschina
相关推荐

2015-12-11 17:24:50

Androidgradle开发

2010-04-21 17:07:54

Windows Pho

2013-07-30 12:37:56

Windows PhoWindows Pho

2013-04-25 16:42:44

Windows Pho反思、建议与忠告

2013-04-19 16:34:56

Windows PhoWindows Pho

2013-04-16 17:02:50

Windows Pho概论

2013-07-30 11:18:37

Windows PhoWindows Pho

2013-04-17 14:00:06

Windows PhoWindows Pho

2011-06-07 12:42:15

Windows Pho

2010-04-08 17:40:23

Windows Pho

2010-04-12 17:32:59

Windows Pho

2010-12-14 18:48:49

微软

2013-07-31 13:13:50

Windows PhoMVVM模式

2013-04-19 16:52:24

Windows PhoWindows Pho

2013-04-19 15:35:54

Windows Pho隔离存储

2012-06-04 14:47:58

Windows Pho

2013-07-31 12:50:39

搭建Windows PWindows Pho

2013-04-17 14:47:19

Windows PhoWindows Pho

2012-08-16 10:35:50

Windows Pho

2013-04-17 13:27:04

Windows PhoWindows Pho
点赞
收藏

51CTO技术栈公众号