wp8, leap motion and a glue called sockets

I’m one of the lucky few who got their hands on a Leap Motion developer device (check out the video above if you’ve never heard of the Leap Motion). It’s a pretty cool device that gives you motion tracking not unlike Kinect but limited to finger and hand movement instead of complete body tracking.

I had the device and needed something to play with and what’s cooler then combining a cool gadget with an awesome smartphone? So I decided to build a small proof-of-concept that would capture finger movement in a WPF application and translate that movement to a moving ellipse in a Windows Phone application.

The Leap Motion’s documentation got me to a moving ellipse in a WPF application pretty fast thanks to the samples and documentation found on their developer portal. It took me a bit more time to get the position of the ellipse send to the phone, I wanted to use Sockets for this (SignalR would be way easier but I didn’t want an extra service running, now I have peer to peer communication).

Here’s how I did it

WPF and the Leap Motion

First, the WPF project. This project will be the socket server and the app that captures the Leap Motion’s output. The application only has one page with this as XAML

Code Snippet
  1. <Window x:Class="LeapWpPoc.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="MainWindow"
  5.         Width="525"
  6.         Height="350">
  7.     <Canvas x:Name="TheCanvas">
  8.         <Ellipse x:Name="TheEllipse"
  9.                  Canvas.Left="211"
  10.                  Canvas.Top="118"
  11.                  Width="70"
  12.                  Height="70"
  13.                  Fill="#FFFF0C00"
  14.                  Stroke="Black" />
  15.         <TextBlock x:Name="TextBlockStatus"
  16.                    Canvas.Left="10"
  17.                    Canvas.Top="10"
  18.                    Foreground="Red"
  19.                    Text="Not connected"
  20.                    TextWrapping="Wrap" />
  21.     </Canvas>
  22. </Window>

Let’s have a look at how to interact with the Leap Motion first.

First thing you need when working with the Leap Motion (apart from the actual device that is) is a reference to LeapCSharp.NET4.0.dll however, you’ll also need Leap.dll and LeapCSharp.dll. Now I find this a bit dirty and I sincerely hope that the Leap Motion team will find a way to fix this but those two libraries aren’t referencable in our project but they need to be present in the application’s directory or it won’t work. What I did is add them as an existing item to the project, set their build action to Content and Copy if newer, at least this way they will always get copied into the build directory of the application.

Next, you’ll needs a class that inherits from Listener (Listener is part of the Leap Motion SDK). Listener is a base class that provides a bunch of virtual methods like OnExit, OnDisconnect, OnConnect and OnFrame. Feel free to override those to add some logging or logic but I’m only using the OnFrame method here. Here’s my Listener class

Code Snippet
  1. class PocListener : Listener
  2. {
  3.     public event EventHandler<FrameDetectedEventArgs> FrameDetected;
  4.  
  5.     public override void OnFrame (Controller controller)
  6.     {
  7.         // Get the most recent frame and report some basic information
  8.         Frame frame = controller.Frame ();
  9.  
  10.         if (FrameDetected != null)
  11.         {
  12.             FrameDetected(this, new FrameDetectedEventArgs(frame));
  13.         }
  14.     }
  15. }

The OnFrame method fires constantly, passing all the movement information, if any, in a frame. If my listener implementation detects a frame the FrameDetected event will fire, passing in the detected frame as an eventarg, FrameDetectedEventArgs is a very basic class that only passes the frame data to whoever is listening to the event.

Code Snippet
  1. public class FrameDetectedEventArgs : EventArgs
  2. {
  3.     public Frame Frame { get; set; }
  4.  
  5.     public FrameDetectedEventArgs(Frame frame)
  6.     {
  7.         Frame = frame;
  8.     }
  9. }

Notice that the OnFrame method needs a Controller as parameter? Controller is the class from the Leap Motion API that talks to the device. I create a new instance of Controller and my Listener in the MainWindow constructor.

<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:5e8744d4-42a7-4711-9a87-a7b25b4e4950" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 500px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Frame</span><span style="background:#ffffff;color:#000000"> _previousFrame;</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Frame</span><span style="background:#ffffff;color:#000000"> _currenFrame;</span></li> <li><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">readonly</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">PocListener</span><span style="background:#ffffff;color:#000000"> _listener;</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">readonly</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Controller</span><span style="background:#ffffff;color:#000000"> _controller;</span></li> <li><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">readonly</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SocketFactory</span><span style="background:#ffffff;color:#000000"> _socketFactory;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> MainWindow()</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000">InitializeComponent();</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000">_listener = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">PocListener</span><span style="background:#ffffff;color:#000000">();</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">_controller = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Controller</span><span style="background:#ffffff;color:#000000">();</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Have the sample listener receive events from the controller</span></li> <li>    <span style="background:#ffffff;color:#000000">_controller.AddListener(_listener);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000">_listener.FrameDetected += ListenerOnFrameDetected;</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>    <p>This is the constructor and some private fields, I need to keep track of both the current frame and the previous one to detect if there’s any change in the position of the hand or fingers. I also have an instance of PocListener (my own Listener class) and of Controller, both get instantiated in the constructor.Next I need to register my Listener in the Controller, that’s done on line 14 and then finally I attach an event handler to the FrameDetected event.</p>  <p>The event handler of the FrameDetected event will be responsible of checking if hands and fingers are detected.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:def5086a-32f7-456c-81e8-59fc338ce6d1" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 500px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> ListenerOnFrameDetected(</span><span style="background:#ffffff;color:#0000ff">object</span><span style="background:#ffffff;color:#000000"> sender, </span><span style="background:#ffffff;color:#2b91af">FrameDetectedEventArgs</span><span style="background:#ffffff;color:#000000"> frameDetectedEventArgs)</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000">_currenFrame = frameDetectedEventArgs.Frame;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (!_currenFrame.Hands.Empty)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Get the first hand</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Hand</span><span style="background:#ffffff;color:#000000"> hand = _currenFrame.Hands[0];</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Check if the hand has any fingers</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">FingerList</span><span style="background:#ffffff;color:#000000"> fingers = hand.Fingers;</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (!fingers.Empty)</span></li> <li>        <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (_previousFrame == </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">) _previousFrame = _currenFrame;</span></li> <li>            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">//check if the current frame is different from the last frame</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (_currenFrame != _previousFrame)</span></li> <li>            <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">                <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">//we only need one finger so we&#39;ll take the first one that&#39;s detected</span></li> <li>                <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Finger</span><span style="background:#ffffff;color:#000000"> finger = fingers[0];</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>                <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">float</span><span style="background:#ffffff;color:#000000"> x = _previousFrame.Fingers[0].TipPosition.x - finger.TipPosition.x;</span></li> <li style="background: #f3f3f3">                <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">float</span><span style="background:#ffffff;color:#000000"> y = _previousFrame.Fingers[0].TipPosition.y - finger.TipPosition.y;</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">                <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">//update the sphere&#39;s position</span></li> <li>                <span style="background:#ffffff;color:#000000">Dispatcher.BeginInvoke((</span><span style="background:#ffffff;color:#2b91af">Action</span><span style="background:#ffffff;color:#000000">)(() =&gt;</span></li> <li style="background: #f3f3f3">                                                <span style="background:#ffffff;color:#000000">{</span></li> <li>                                                    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Canvas</span><span style="background:#ffffff;color:#000000">.SetTop(TheEllipse, </span><span style="background:#ffffff;color:#2b91af">Canvas</span><span style="background:#ffffff;color:#000000">.GetTop(TheEllipse) + y);</span></li> <li style="background: #f3f3f3">                                                    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Canvas</span><span style="background:#ffffff;color:#000000">.SetLeft(TheEllipse, </span><span style="background:#ffffff;color:#2b91af">Canvas</span><span style="background:#ffffff;color:#000000">.GetLeft(TheEllipse) - x);</span></li> <li>                                                <span style="background:#ffffff;color:#000000">}));</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>                <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">//set this frame as the previous one and get ready to receive a new frame</span></li> <li style="background: #f3f3f3">                <span style="background:#ffffff;color:#000000">_previousFrame = _currenFrame;</span></li> <li>            <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">}</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>First we check if the previous frame has the same information as the current frame, if it does there’s no need to update the ellipse’s position. </p>  <p>If a hand and fingers are detected I select the first detected finger, because that’s currently the only one I’m interested in. Since all the Leap Motion actions are happening on a separate thread I need to invoke the UI thread to update the ellipse’s position, that’s what’s happening on line 25. The position of a UIElement in a Canvas in XAML is set through attached properties (Canvas.Left=”177” for example) to set these in code we use Canvas.SetLeft. To determine the new location of the ellipse I take the X and Y positions of the first finger in the previous frame and substract the X and Y of the first finger in the current frame. The new Y value gets added to the Canvas.Top of the ellipse and the new X value gets subtracted&#160; from the Canvas.Left value. Last but not least I set the previousframe to the currentframe. </p>  <p>That’s all the code you need to get an ellipse moving in a canvas with the Leap Motion. So part 1 is a great success. Now onto the bigger challenge, getting a similar ellipse to move in a Windows Phone project.</p>  <h2>Windows Phone and sockets</h2>  <p>Implementing sockets to make devices talk to each other over the wire can be challenging but it’s also very rewarding and just plain fun once it works. I haven’t worked with sockets before so I had a real blast trying to figure this out and I went through the roof once that ellipse started moving on the Windows Phone emulator <img class="wlEmoticon wlEmoticon-smile" style="border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none" alt="Glimlach" src="http://www.spikie.be/blog/images/wlEmoticon-smile_17.png" />. Before we dive into the sockets, let’s have a quick look at the MainPage.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:645eb56c-d2e7-4c9b-b10f-29a96d70c5d1" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 300px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">Canvas</span><span style="background:#ffffff;color:#ff0000"> x</span><span style="background:#ffffff;color:#0000ff">:</span><span style="background:#ffffff;color:#ff0000">Name</span><span style="background:#ffffff;color:#0000ff">=&quot;TheCanvas&quot;&gt;</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">Ellipse</span><span style="background:#ffffff;color:#ff0000"> x</span><span style="background:#ffffff;color:#0000ff">:</span><span style="background:#ffffff;color:#ff0000">Name</span><span style="background:#ffffff;color:#0000ff">=&quot;TheEllipse&quot;</span></li> <li>            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#ff0000"> Canvas.Left</span><span style="background:#ffffff;color:#0000ff">=&quot;302&quot;</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#ff0000"> Canvas.Top</span><span style="background:#ffffff;color:#0000ff">=&quot;186&quot;</span></li> <li>            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#ff0000"> Width</span><span style="background:#ffffff;color:#0000ff">=&quot;70&quot;</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#ff0000"> Height</span><span style="background:#ffffff;color:#0000ff">=&quot;70&quot;</span></li> <li>            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#ff0000"> Fill</span><span style="background:#ffffff;color:#0000ff">=&quot;#FFFF0C00&quot;</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#ff0000"> Stroke</span><span style="background:#ffffff;color:#0000ff">=&quot;Black&quot; /&gt;</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">&lt;</span><span style="background:#ffffff;color:#a31515">TextBlock</span><span style="background:#ffffff;color:#ff0000"> x</span><span style="background:#ffffff;color:#0000ff">:</span><span style="background:#ffffff;color:#ff0000">Name</span><span style="background:#ffffff;color:#0000ff">=&quot;TextBlockStatus&quot;</span></li> <li style="background: #f3f3f3">              <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#ff0000"> Canvas.Left</span><span style="background:#ffffff;color:#0000ff">=&quot;10&quot;</span></li> <li>              <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#ff0000"> Canvas.Top</span><span style="background:#ffffff;color:#0000ff">=&quot;10&quot;</span></li> <li style="background: #f3f3f3">              <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#ff0000"> Foreground</span><span style="background:#ffffff;color:#0000ff">=&quot;Red&quot;</span></li> <li>              <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#ff0000"> Text</span><span style="background:#ffffff;color:#0000ff">=&quot;Not connected&quot;</span></li> <li style="background: #f3f3f3">              <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#ff0000"> TextWrapping</span><span style="background:#ffffff;color:#0000ff">=&quot;Wrap&quot; /&gt;</span></li> <li><span style="background:#ffffff;color:#0000ff">&lt;/</span><span style="background:#ffffff;color:#a31515">Canvas</span><span style="background:#ffffff;color:#0000ff">&gt;</span></li> </ol> </div> </div> </div>  <p>Exactly the same controls as in the WPF project, nothing spectacular here. Let’s have a look at the code behind the MainPage.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:7f18e40f-abd8-47f8-a041-20f69765b64b" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 500px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">partial</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MainPage</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#2b91af">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SocketClient</span><span style="background:#ffffff;color:#000000"> _client;</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">const</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">int</span><span style="background:#ffffff;color:#000000"> Port = 8000;</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">const</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> IpAddress = </span><span style="background:#ffffff;color:#a31515">&quot;10.16.79.70&quot;</span><span style="background:#ffffff;color:#000000">;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Constructor</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> MainPage()</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">InitializeComponent();</span></li> <li>        <span style="background:#ffffff;color:#000000">_client = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SocketClient</span><span style="background:#ffffff;color:#000000">();</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>        <span style="background:#ffffff;color:#000000">_client.OnConnected += (sender, args) =&gt; Dispatcher.BeginInvoke(() =&gt;</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">{</span></li> <li>                <span style="background:#ffffff;color:#000000">TextBlockStatus.Text = </span><span style="background:#ffffff;color:#a31515">&quot;Connected&quot;</span><span style="background:#ffffff;color:#000000">;</span></li> <li style="background: #f3f3f3">                <span style="background:#ffffff;color:#000000">TextBlockStatus.Foreground = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SolidColorBrush</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#2b91af">Colors</span><span style="background:#ffffff;color:#000000">.Green);</span></li> <li>            <span style="background:#ffffff;color:#000000">});</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">_client.OnMessageReceived += (sender, args) =&gt; Dispatcher.BeginInvoke(() =&gt; MoveBall(args.Response));</span></li> <li>        <span style="background:#ffffff;color:#000000">_client.Connect(IpAddress, Port);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>        <span style="background:#ffffff;color:#000000">_client.Receive();</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> MoveBall(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> response)</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">response = response.Replace(</span><span style="background:#ffffff;color:#a31515">&#39;,&#39;</span><span style="background:#ffffff;color:#000000">, </span><span style="background:#ffffff;color:#a31515">&#39;.&#39;</span><span style="background:#ffffff;color:#000000">);</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">var</span><span style="background:#ffffff;color:#000000"> coordinates = response.Split(</span><span style="background:#ffffff;color:#a31515">&#39;;&#39;</span><span style="background:#ffffff;color:#000000">);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">float</span><span style="background:#ffffff;color:#000000"> y = </span><span style="background:#ffffff;color:#0000ff">float</span><span style="background:#ffffff;color:#000000">.Parse(coordinates[0]);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">float</span><span style="background:#ffffff;color:#000000"> x = </span><span style="background:#ffffff;color:#0000ff">float</span><span style="background:#ffffff;color:#000000">.Parse(coordinates[1]);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Canvas</span><span style="background:#ffffff;color:#000000">.SetTop(TheEllipse, y);</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Canvas</span><span style="background:#ffffff;color:#000000">.SetLeft(TheEllipse, x);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>First some fields, don’t worry about the SocketClient class, we’ll get to that in a minute. Some constants holding the IP address and the port of the server (don’t forget to change this IP address to the address of your own pc!)</p>  <p>In the constructor we instantiate the SocketClient instance and handle its two events. The OnConnected event is going to change the text of the TextBlock to “Connected” and the OnMessageReceived event handler will move the ellipse.</p>  <p>The MoveBall() method will do the actual moving. The message that we will receive will be a string that has the Y and X of the ellipse in the WPF application seperated by a semicolon. The problem I had here was that instead of a dot to separate the decimals .NET had changed it into a comma (which is the default decimal sign in Belgium) so I need to change that back. I then split up the string using the semicolon as split character, parse the values into a float and set the ellipse to its new position. Let’s get serious and dive into the socket stuff now.</p>  <p>Sockets provide us with TCP and UDP communication, next to a whole bunch of other features. This app will use a TCP connection between WPF and a Windows Phone application. Since we’re currently looking at the Windows Phone app, let’s continue there. I’ve added a class called SocketClient that takes care of connection a socket, sending and receiving messages. Let’s start with the fields and constructor.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:f1e7c86f-d048-4c8a-986a-e95eca5d4ca8" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 500px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#008000">// Cached Socket object that will be used by each call for the lifetime of this class</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#2b91af">Socket</span><span style="background:#ffffff;color:#000000"> _socket;</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#008000">// Signaling object used to notify when an asynchronous operation is completed</span></li> <li><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ManualResetEvent</span><span style="background:#ffffff;color:#000000"> _clientDone;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#008000">// Define a timeout in milliseconds for each asynchronous call. If a response is not received within this</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#008000">// timeout period, the call is aborted.</span></li> <li><span style="background:#ffffff;color:#0000ff">const</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">int</span><span style="background:#ffffff;color:#000000"> TimeoutMilliseconds = 5000;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#008000">// The maximum size of the data buffer to use with the asynchronous socket methods</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">const</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">int</span><span style="background:#ffffff;color:#000000"> MaxBufferSize = 2048;</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">event</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">EventHandler</span><span style="background:#ffffff;color:#000000">&lt;</span><span style="background:#ffffff;color:#2b91af">MessageReceivedEventArgs</span><span style="background:#ffffff;color:#000000">&gt; OnMessageReceived;</span></li> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">event</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">EventHandler</span><span style="background:#ffffff;color:#000000"> OnConnected;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> SocketClient()</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000">_clientDone = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ManualResetEvent</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#0000ff">false</span><span style="background:#ffffff;color:#000000">);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>    <p>First field is the actual socket that we’ll be using, second one is a reset event that we can use to make a thread block while waiting for an event to fire. The timeout is the max amount of time that the reset event will block a thread. The buffersize is the size of the buffer for socket messages. The two events are fired when the app receives a socket message or when a socket connects.</p>  <p>The most important function of the SocketClient class that I’m building here is to connect two sockets.</p>  <p>   <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:d8c5d9d0-e518-4ae4-b916-7dec1271e496" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 500px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> Connect(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> hostName, </span><span style="background:#ffffff;color:#0000ff">int</span><span style="background:#ffffff;color:#000000"> portNumber)</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> result = </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Empty;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Create DnsEndPoint. The hostName and port are passed in to this method.</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">DnsEndPoint</span><span style="background:#ffffff;color:#000000"> hostEntry = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">DnsEndPoint</span><span style="background:#ffffff;color:#000000">(hostName, portNumber);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Create a stream-based, TCP socket using the InterNetwork Address Family. </span></li> <li>    <span style="background:#ffffff;color:#000000">_socket = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Socket</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#2b91af">AddressFamily</span><span style="background:#ffffff;color:#000000">.InterNetwork, </span><span style="background:#ffffff;color:#2b91af">SocketType</span><span style="background:#ffffff;color:#000000">.Stream, </span><span style="background:#ffffff;color:#2b91af">ProtocolType</span><span style="background:#ffffff;color:#000000">.Tcp);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Create a SocketAsyncEventArgs object to be used in the connection request</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">SocketAsyncEventArgs</span><span style="background:#ffffff;color:#000000"> socketEventArg = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SocketAsyncEventArgs</span><span style="background:#ffffff;color:#000000"> {RemoteEndPoint = hostEntry};</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">socketEventArg.Completed += (sender, args) =&gt;</span></li> <li>                                        <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">                                            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Retrieve the result of this request</span></li> <li>                                            <span style="background:#ffffff;color:#000000">result = args.SocketError.ToString();</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>                                            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Signal that the request is complete, unblocking the UI thread</span></li> <li style="background: #f3f3f3">                                            <span style="background:#ffffff;color:#000000">_clientDone.Set();</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">                                            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (OnConnected == </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">) </span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000">;</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">                                            <span style="background:#ffffff;color:#000000">OnConnected(</span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">, </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">EventArgs</span><span style="background:#ffffff;color:#000000">());</span></li> <li>                                        <span style="background:#ffffff;color:#000000">};</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Sets the state of the event to nonsignaled, causing threads to block</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">_clientDone.Reset();</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Make an asynchronous Connect request over the socket</span></li> <li>    <span style="background:#ffffff;color:#000000">_socket.ConnectAsync(socketEventArg);</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// If no response comes back within this time then proceed</span></li> <li>    <span style="background:#ffffff;color:#000000">_clientDone.WaitOne(TimeoutMilliseconds);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000"> result;</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div> </p>  <p>The connect method takes in two parameters, the hostname (or IP address) and the portnumber of the socket we want to connect to. Based on these two parameters we create a DnsEndPoint that will be passed to the server socket as being the remote endpoint so that the server socket knows where to send his messages. Next we instantiate the Socket, stating that it’s using an internal IPv4 network, a stream socket and the TCP protocol. Now that we have a socket and an endpoint we’ll need some eventargs, those args will be passed onto the server. Once the connection succeeds (or fails) the Completed event on the SocketAsyncEventArgs will fire, in that event handler we’ll trigger the OnConnected event. With that in place we call the Reset() method on the ManualResetEvent to set the event to nonsignaled, call the ConnectAsync() method on the Socket and pass in the eventargs and finally blocking the thread for a certain time to allow the socket time to connect.</p>  <p>So now that our client can connect to a socket, let’s build something to send messages to the connected socket. From the Windows Phone 8 version it looks like this</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:7c0f093d-a764-46b0-b077-2d2905c59935" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 500px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Send(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> data)</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000">data = data + </span><span style="background:#ffffff;color:#a31515">&quot;&lt;EOF&gt;&quot;</span><span style="background:#ffffff;color:#000000">;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (_socket != </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">SocketAsyncEventArgs</span><span style="background:#ffffff;color:#000000"> socketEventArg = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SocketAsyncEventArgs</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">{</span></li> <li>                <span style="background:#ffffff;color:#000000">RemoteEndPoint = _socket.RemoteEndPoint,</span></li> <li style="background: #f3f3f3">                <span style="background:#ffffff;color:#000000">UserToken = </span><span style="background:#ffffff;color:#0000ff">null</span></li> <li>            <span style="background:#ffffff;color:#000000">};</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>        <span style="background:#ffffff;color:#000000">socketEventArg.Completed += (sender, args) =&gt;</span></li> <li style="background: #f3f3f3">                                        <span style="background:#ffffff;color:#000000">{</span></li> <li>                                            <span style="background:#ffffff;color:#000000">_clientDone.Set();</span></li> <li style="background: #f3f3f3">                                        <span style="background:#ffffff;color:#000000">};</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Add the data to be sent into the buffer</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">byte</span><span style="background:#ffffff;color:#000000">[] payload = </span><span style="background:#ffffff;color:#2b91af">Encoding</span><span style="background:#ffffff;color:#000000">.UTF8.GetBytes(data);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">socketEventArg.SetBuffer(payload, 0, payload.Length);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Sets the state of the event to nonsignaled, causing threads to block</span></li> <li>        <span style="background:#ffffff;color:#000000">_clientDone.Reset();</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Make an asynchronous Send request over the socket</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">_socket.SendAsync(socketEventArg);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// If no response comes back within this time then proceed</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">_clientDone.WaitOne(TimeoutMilliseconds);</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>We get in the message as a parameter, at the end of the message I add “&lt;EOF&gt;” just to make sure that I only get the part that I need at the server side and that the message has been delivered in full. If at this point the socket is null then it isn’t connected yet. If it isn’t we once again instantiate SocketAsyncEventArgs. The data gets serialized into a byte array and set as a buffer in the eventargs. Set the ManualResetEvent to nonsignaled, start sending the message over the socket async and block the thread. </p>  <p>And last but not least there’s the code to receive messages on the socket.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:302ec5d1-addf-45c3-8658-572cb127a313" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 500px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Receive()</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (_socket != </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">SocketAsyncEventArgs</span><span style="background:#ffffff;color:#000000"> socketEventArg = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SocketAsyncEventArgs</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">{</span></li> <li>                <span style="background:#ffffff;color:#000000">RemoteEndPoint = _socket.RemoteEndPoint</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">};</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Setup the buffer to receive the data</span></li> <li>        <span style="background:#ffffff;color:#000000">socketEventArg.SetBuffer(</span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> Byte[MaxBufferSize], 0, MaxBufferSize);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>        <span style="background:#ffffff;color:#000000">socketEventArg.Completed += (sender, args) =&gt;</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">{</span></li> <li>                <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (args.SocketError == </span><span style="background:#ffffff;color:#2b91af">SocketError</span><span style="background:#ffffff;color:#000000">.Success)</span></li> <li style="background: #f3f3f3">                <span style="background:#ffffff;color:#000000">{</span></li> <li>                    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Retrieve the data from the buffer</span></li> <li style="background: #f3f3f3">                    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> response = </span><span style="background:#ffffff;color:#2b91af">Encoding</span><span style="background:#ffffff;color:#000000">.UTF8.GetString(args.Buffer, args.Offset, args.BytesTransferred);</span></li> <li>                    <span style="background:#ffffff;color:#000000">response = response.Trim(</span><span style="background:#ffffff;color:#a31515">&#39;&#92;0&#39;</span><span style="background:#ffffff;color:#000000">);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>                    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (response.Contains(</span><span style="background:#ffffff;color:#a31515">&quot;&lt;EOF&gt;&quot;</span><span style="background:#ffffff;color:#000000">))</span></li> <li style="background: #f3f3f3">                    <span style="background:#ffffff;color:#000000">{</span></li> <li>                        <span style="background:#ffffff;color:#000000">response = response.Substring(0, response.IndexOf(</span><span style="background:#ffffff;color:#a31515">&quot;&lt;EOF&gt;&quot;</span><span style="background:#ffffff;color:#000000">));</span></li> <li style="background: #f3f3f3">                        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (OnMessageReceived != </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">)</span></li> <li>                            <span style="background:#ffffff;color:#000000">OnMessageReceived(</span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">, </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MessageReceivedEventArgs</span><span style="background:#ffffff;color:#000000">(response));</span></li> <li style="background: #f3f3f3">                    <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">                    <span style="background:#ffffff;color:#000000">Receive();</span></li> <li>                <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>                <span style="background:#ffffff;color:#000000">_clientDone.Set();</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">};</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Sets the state of the event to nonsignaled, causing threads to block</span></li> <li>        <span style="background:#ffffff;color:#000000">_clientDone.Reset();</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Make an asynchronous Receive request over the socket</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">_socket.ReceiveAsync(socketEventArg);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// If no response comes back within this time then proceed</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">_clientDone.WaitOne(TimeoutMilliseconds);</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>So the same story with the null check on the socket and creating of the SocketEventArgs. Once the Completed event fires we’ll check if the receive was successful&#160; and if the received message contains “&lt;EOF&gt;”, if it does we take everything before &lt;EOF&gt; and pass it in the MessageReceivedEventArgs that go with the MessageReceived event.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:9d9b4c7e-6308-4346-977d-35da9a1c05ef" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 300px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">MessageReceivedEventArgs</span><span style="background:#ffffff;color:#000000"> : </span><span style="background:#ffffff;color:#2b91af">EventArgs</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#2b91af">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> Response { </span><span style="background:#ffffff;color:#0000ff">get</span><span style="background:#ffffff;color:#000000">; </span><span style="background:#ffffff;color:#0000ff">set</span><span style="background:#ffffff;color:#000000">; }</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> MessageReceivedEventArgs(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> response)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000">Response = response;</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>Once everthing is handled we call the Receive method again so it’s ready to start receiving the next message.</p>  <p>And that’s basically all the logic for a socket connection on the Windows Phone side of things. The only thing left to do in the app is change the MainPage’s constructor to initialize the SocketClient and add some fields.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:1977ef61-9338-4503-80af-150a7716d6fd" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 500px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SocketClient</span><span style="background:#ffffff;color:#000000"> _client;</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">const</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">int</span><span style="background:#ffffff;color:#000000"> Port = 8000;</span></li> <li><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">const</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> IpAddress = </span><span style="background:#ffffff;color:#a31515">&quot;10.16.79.70&quot;</span><span style="background:#ffffff;color:#000000">;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li><span style="background:#ffffff;color:#008000">// Constructor</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> MainPage()</span></li> <li><span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">InitializeComponent();</span></li> <li>    <span style="background:#ffffff;color:#000000">_client = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SocketClient</span><span style="background:#ffffff;color:#000000">();</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000">_client.OnConnected += (sender, args) =&gt; Dispatcher.BeginInvoke(() =&gt;</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">{</span></li> <li>            <span style="background:#ffffff;color:#000000">TextBlockStatus.Text = </span><span style="background:#ffffff;color:#a31515">&quot;Connected&quot;</span><span style="background:#ffffff;color:#000000">;</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">TextBlockStatus.Foreground = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SolidColorBrush</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#2b91af">Colors</span><span style="background:#ffffff;color:#000000">.Green);</span></li> <li>        <span style="background:#ffffff;color:#000000">});</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">_client.OnMessageReceived += (sender, args) =&gt; Dispatcher.BeginInvoke(() =&gt; MoveBall(args.Response));</span></li> <li>    <span style="background:#ffffff;color:#000000">_client.Connect(IpAddress, Port);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000">_client.Receive();</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>The constructor instantiates the SocketClient, attaches an handler to the OnConnected event to update the textbox with the connection status and handle the OnMessageReceived event to update the position of the ellipse. Don’t forget to update the IP address to the one from your own pc!</p>  <h2>Back to WPF!</h2>  <p>Now that our Windows Phone app is ready, it’s time to implement the socket server. As mentioned before, the WPF app that gets input from the Leap Motion will serve as socket server.</p>  <p>I’ve added a class to the WPF project called SocketFactory, it serves the same function as the SocketClient class in the Windows Phone project but from a server point of view. The way to build and use a socket in full blown .net 4.5 differs a bit from how we did it in Windows Phone. First we’ll need a state class, this contains a socket, the buffersize, a byte array to function as the buffer and a stringbuilder to recompose the message.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:07b9d0f9-cb05-4447-b980-722385a52c46" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 300px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#008000">// State object for reading client data asynchronously</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">class</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">StateObject</span></li> <li><span style="background:#ffffff;color:#2b91af">{</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Client  socket.</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Socket</span><span style="background:#ffffff;color:#000000"> WorkSocket = </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">;</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Size of receive buffer.</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">const</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">int</span><span style="background:#ffffff;color:#000000"> BufferSize = 1024;</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Receive buffer.</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">byte</span><span style="background:#ffffff;color:#000000">[] Buffer = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">byte</span><span style="background:#ffffff;color:#000000">[BufferSize];</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Received data string.</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">StringBuilder</span><span style="background:#ffffff;color:#000000"> Sb = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">StringBuilder</span><span style="background:#ffffff;color:#000000">();</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>Next, we’ll need some fields in the SocketFactory class</p>    <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:a6e23560-c58b-4063-b73a-732eab4e0f75" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 300px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#008000">// Thread signal.</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">static</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ManualResetEvent</span><span style="background:#ffffff;color:#000000"> AllDone = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">ManualResetEvent</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#0000ff">false</span><span style="background:#ffffff;color:#000000">);</span></li> <li><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">StateObject</span><span style="background:#ffffff;color:#000000"> _state;</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">event</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">EventHandler</span><span style="background:#ffffff;color:#000000"> OnConnected;</span></li> </ol> </div> </div> </div>  <p>And here’s the function to receive a connection request</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:c2146494-233d-4962-8fda-5f55d44de61e" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 500px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Start()</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">IPHostEntry</span><span style="background:#ffffff;color:#000000"> ipHostInfo = </span><span style="background:#ffffff;color:#2b91af">Dns</span><span style="background:#ffffff;color:#000000">.GetHostEntry(</span><span style="background:#ffffff;color:#2b91af">Dns</span><span style="background:#ffffff;color:#000000">.GetHostName());</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">IPAddress</span><span style="background:#ffffff;color:#000000"> ipAddress = ipHostInfo.AddressList[3];</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">IPEndPoint</span><span style="background:#ffffff;color:#000000"> localEndPoint = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">IPEndPoint</span><span style="background:#ffffff;color:#000000">(ipAddress, 8000);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Socket</span><span style="background:#ffffff;color:#000000"> listener = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Socket</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#2b91af">AddressFamily</span><span style="background:#ffffff;color:#000000">.InterNetwork, </span><span style="background:#ffffff;color:#2b91af">SocketType</span><span style="background:#ffffff;color:#000000">.Stream, </span><span style="background:#ffffff;color:#2b91af">ProtocolType</span><span style="background:#ffffff;color:#000000">.Tcp);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Bind the socket to the local endpoint and listen for incoming connections.</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">try</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">listener.Bind(localEndPoint);</span></li> <li>        <span style="background:#ffffff;color:#000000">listener.Listen(100);</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">while</span><span style="background:#ffffff;color:#000000"> (</span><span style="background:#ffffff;color:#0000ff">true</span><span style="background:#ffffff;color:#000000">)</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">{</span></li> <li>            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Set the event to nonsignaled state.</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">AllDone.Reset();</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Start an asynchronous socket to listen for connections.</span></li> <li>            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Console</span><span style="background:#ffffff;color:#000000">.WriteLine(</span><span style="background:#ffffff;color:#a31515">&quot;Waiting for a connection...&quot;</span><span style="background:#ffffff;color:#000000">);</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">listener.BeginAccept(AcceptCallback, listener);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Wait until a connection is made before continuing.</span></li> <li>            <span style="background:#ffffff;color:#000000">AllDone.WaitOne();</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (OnConnected == </span><span style="background:#ffffff;color:#0000ff">null</span><span style="background:#ffffff;color:#000000">) </span><span style="background:#ffffff;color:#0000ff">return</span><span style="background:#ffffff;color:#000000">;</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>            <span style="background:#ffffff;color:#000000">OnConnected(</span><span style="background:#ffffff;color:#0000ff">this</span><span style="background:#ffffff;color:#000000">, </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">EventArgs</span><span style="background:#ffffff;color:#000000">());</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">catch</span><span style="background:#ffffff;color:#000000"> (</span><span style="background:#ffffff;color:#2b91af">Exception</span><span style="background:#ffffff;color:#000000"> e)</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Console</span><span style="background:#ffffff;color:#000000">.WriteLine(e.ToString());</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">}</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>We declare a socket called listener, pass it the same parameters as we did for Windows Phone, stating that it’s local network, streaming and using the TCP protocol. We need to bind this socket to an IPEndPoint, to create an IPEndPoint we need an IPAddress and a port. Lines 3 and 4 are used to getting the computer’s IP address from its hostname. Once we have that we can bind the socket to the endpoint. Make sure that the port you set here is the same port you try to connect to in the Windows Phone app. Once the socket connects the callback fires, in the callback we start receiving data from the connected client.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:a6af5766-433b-4616-b760-caf7050d1f7e" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 300px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> AcceptCallback(</span><span style="background:#ffffff;color:#2b91af">IAsyncResult</span><span style="background:#ffffff;color:#000000"> ar)</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Signal the main thread to continue.</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">AllDone.Set();</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Get the socket that handles the client request.</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Socket</span><span style="background:#ffffff;color:#000000"> listener = (</span><span style="background:#ffffff;color:#2b91af">Socket</span><span style="background:#ffffff;color:#000000">)ar.AsyncState;</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Socket</span><span style="background:#ffffff;color:#000000"> handler = listener.EndAccept(ar);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Create the state object.</span></li> <li>    <span style="background:#ffffff;color:#000000">_state = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">StateObject</span><span style="background:#ffffff;color:#000000"> { WorkSocket = handler };</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000">handler.BeginReceive(_state.Buffer, 0, </span><span style="background:#ffffff;color:#2b91af">StateObject</span><span style="background:#ffffff;color:#000000">.BufferSize, 0, ReadCallback, _state);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>Once data is received, the ReadCallback fires</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:9dcf345e-c6d6-4114-afea-d64e9e56575c" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 500px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> ReadCallback(</span><span style="background:#ffffff;color:#2b91af">IAsyncResult</span><span style="background:#ffffff;color:#000000"> ar)</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">StateObject</span><span style="background:#ffffff;color:#000000"> state = (</span><span style="background:#ffffff;color:#2b91af">StateObject</span><span style="background:#ffffff;color:#000000">)ar.AsyncState;</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Socket</span><span style="background:#ffffff;color:#000000"> handler = state.WorkSocket;</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">int</span><span style="background:#ffffff;color:#000000"> bytesRead = handler.EndReceive(ar);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (bytesRead &gt; 0)</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// There  might be more data, so store the data received so far.</span></li> <li>        <span style="background:#ffffff;color:#000000">state.Sb.Append(</span><span style="background:#ffffff;color:#2b91af">Encoding</span><span style="background:#ffffff;color:#000000">.ASCII.GetString(</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">state.Buffer, 0, bytesRead));</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Check for end-of-file tag. If it is not there, read </span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// more data.</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> content = state.Sb.ToString();</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">if</span><span style="background:#ffffff;color:#000000"> (content.IndexOf(</span><span style="background:#ffffff;color:#a31515">&quot;&lt;EOF&gt;&quot;</span><span style="background:#ffffff;color:#000000">) &gt; -1)</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">{</span></li> <li>            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Console</span><span style="background:#ffffff;color:#000000">.WriteLine(</span><span style="background:#ffffff;color:#a31515">&quot;Read {</span><span style="background:#ffffff;color:#3cb371">0}</span><span style="background:#ffffff;color:#a31515"> bytes from socket. &#92;n Data : {</span><span style="background:#ffffff;color:#3cb371">1}</span><span style="background:#ffffff;color:#a31515">&quot;</span><span style="background:#ffffff;color:#000000">,</span></li> <li style="background: #f3f3f3">                <span style="background:#ffffff;color:#000000">content.Length, content);</span></li> <li>        <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">else</span></li> <li>        <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Not all data received. Get more.</span></li> <li>            <span style="background:#ffffff;color:#000000">handler.BeginReceive(state.Buffer, 0, </span><span style="background:#ffffff;color:#2b91af">StateObject</span><span style="background:#ffffff;color:#000000">.BufferSize, 0, ReadCallback, state);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">}</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>We can get the stateobject and socket from the IAsyncResult and we start reading until we encounter “&lt;EOF&gt;”, once everything is received we write it out in the output window. Now in this example the server won’t actually be receiving any messages, I’ve just put in this method in case you want to enhance it or have some use for the code.</p>  <p>What is important in this sample is the Send method, this will send a message over the connected socket to the client.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:a7a95953-a45d-445e-8930-4cec5574cf54" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 300px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Send(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> data)</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000">Send(_state.WorkSocket, data);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> Send(</span><span style="background:#ffffff;color:#2b91af">Socket</span><span style="background:#ffffff;color:#000000"> handler, </span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000"> data)</span></li> <li><span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">data = data + </span><span style="background:#ffffff;color:#a31515">&quot;&lt;EOF&gt;&quot;</span><span style="background:#ffffff;color:#000000">;</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Convert the string data to byte data using ASCII encoding.</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">byte</span><span style="background:#ffffff;color:#000000">[] byteData = </span><span style="background:#ffffff;color:#2b91af">Encoding</span><span style="background:#ffffff;color:#000000">.ASCII.GetBytes(data);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Begin sending the data to the remote device.</span></li> <li>    <span style="background:#ffffff;color:#000000">handler.BeginSend(byteData, 0, byteData.Length, 0, SendCallback, handler);</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>I’ve split up the Send into two methods, the public one just receives the message we want to send and passes it trough to the private one, also passing in the socket to use. This way the application itself doesn’t need to worry about selecting a socket, let the socketFactory deal with that. The Send method adds the end of file part to the message, serializes it into a byte array and sends it over the socket. Once the send is complete, the callback will fire.</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:c70bc3d2-3508-411f-95a7-73f21ec1a2d5" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 300px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">void</span><span style="background:#ffffff;color:#000000"> SendCallback(</span><span style="background:#ffffff;color:#2b91af">IAsyncResult</span><span style="background:#ffffff;color:#000000"> ar)</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">try</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">{</span></li> <li>        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Retrieve the socket from the state object.</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Socket</span><span style="background:#ffffff;color:#000000"> handler = (</span><span style="background:#ffffff;color:#2b91af">Socket</span><span style="background:#ffffff;color:#000000">)ar.AsyncState;</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">handler.EndSend(ar);</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#0000ff">catch</span><span style="background:#ffffff;color:#000000"> (</span><span style="background:#ffffff;color:#2b91af">Exception</span><span style="background:#ffffff;color:#000000"> e)</span></li> <li>    <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Console</span><span style="background:#ffffff;color:#000000">.WriteLine(e.ToString());</span></li> <li>    <span style="background:#ffffff;color:#000000">}</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>  <p>I’m not really doing anything in the callback, but this would be the perfect place to check for successful delivery and maybe notifying the UI thread to show a confirmation or something similar.</p>  <p>Now that our socket infrastructure is in place and we have a client updating a UI based on the received messages, it’s time to finish this sample by letting the server send the coordinates of the ellipse. In the MainWindow add a field for the socket factory. (line 5 is the extra field)</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:fa0824a6-58fc-4c46-a3fb-d32cb35bf128" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 300px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Frame</span><span style="background:#ffffff;color:#000000"> _previousFrame;</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Frame</span><span style="background:#ffffff;color:#000000"> _currenFrame;</span></li> <li><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">readonly</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">PocListener</span><span style="background:#ffffff;color:#000000"> _listener;</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">readonly</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Controller</span><span style="background:#ffffff;color:#000000"> _controller;</span></li> <li><span style="background:#ffffff;color:#0000ff">private</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#0000ff">readonly</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SocketFactory</span><span style="background:#ffffff;color:#000000"> _socketFactory;</span></li> </ol> </div> </div> </div>  <p>With the new field in place, replace (or update) the constructor to this</p>  <div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:658508c0-4a73-4dc2-8c87-a135f80ab4be" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background: #ddd; max-height: 500px; overflow: auto"> <ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;"> <li><span style="background:#ffffff;color:#0000ff">public</span><span style="background:#ffffff;color:#000000"> MainWindow()</span></li> <li style="background: #f3f3f3"><span style="background:#ffffff;color:#000000">{</span></li> <li>    <span style="background:#ffffff;color:#000000">InitializeComponent();</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000">_socketFactory = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SocketFactory</span><span style="background:#ffffff;color:#000000">();</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">_socketFactory.OnConnected += (sender, args) =&gt; Dispatcher.BeginInvoke((</span><span style="background:#ffffff;color:#2b91af">Action</span><span style="background:#ffffff;color:#000000">) (() =&gt;</span></li> <li>        <span style="background:#ffffff;color:#000000">{</span></li> <li style="background: #f3f3f3">            <span style="background:#ffffff;color:#000000">TextBlockStatus.Text = </span><span style="background:#ffffff;color:#a31515">&quot;Connected&quot;</span><span style="background:#ffffff;color:#000000">;</span></li> <li>            <span style="background:#ffffff;color:#000000">TextBlockStatus.Foreground = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">SolidColorBrush</span><span style="background:#ffffff;color:#000000">(</span><span style="background:#ffffff;color:#2b91af">Colors</span><span style="background:#ffffff;color:#000000">.Green);</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">}));</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Task</span><span style="background:#ffffff;color:#000000">.Run(() =&gt; _socketFactory.Start());</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">_listener = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">PocListener</span><span style="background:#ffffff;color:#000000">();</span></li> <li>    <span style="background:#ffffff;color:#000000">_controller = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Controller</span><span style="background:#ffffff;color:#000000">();</span></li> <li style="background: #f3f3f3">&nbsp;</li> <li>    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#008000">// Have the sample listener receive events from the controller</span></li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">_controller.AddListener(_listener);</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">_listener.FrameDetected += ListenerOnFrameDetected;</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000"></span><span style="background:#ffffff;color:#2b91af">Timer</span><span style="background:#ffffff;color:#000000"> timer = </span><span style="background:#ffffff;color:#0000ff">new</span><span style="background:#ffffff;color:#000000"> </span><span style="background:#ffffff;color:#2b91af">Timer</span><span style="background:#ffffff;color:#000000">(200);</span></li> <li>    <span style="background:#ffffff;color:#000000">timer.Elapsed += (sender, args) =&gt; Dispatcher.BeginInvoke((</span><span style="background:#ffffff;color:#2b91af">Action</span><span style="background:#ffffff;color:#000000">)(() =&gt;</span></li> <li style="background: #f3f3f3">        <span style="background:#ffffff;color:#000000">_socketFactory.Send(</span><span style="background:#ffffff;color:#0000ff">string</span><span style="background:#ffffff;color:#000000">.Format(</span><span style="background:#ffffff;color:#a31515">&quot;{</span><span style="background:#ffffff;color:#3cb371">0}</span><span style="background:#ffffff;color:#a31515">;{</span><span style="background:#ffffff;color:#3cb371">1}</span><span style="background:#ffffff;color:#a31515">&quot;</span><span style="background:#ffffff;color:#000000">, </span><span style="background:#ffffff;color:#2b91af">Canvas</span><span style="background:#ffffff;color:#000000">.GetTop(TheEllipse), </span><span style="background:#ffffff;color:#2b91af">Canvas</span><span style="background:#ffffff;color:#000000">.GetLeft(TheEllipse)))));</span></li> <li>&nbsp;</li> <li style="background: #f3f3f3">    <span style="background:#ffffff;color:#000000">timer.Start();</span></li> <li><span style="background:#ffffff;color:#000000">}</span></li> </ol> </div> </div> </div>    <p>We instantiate the SocketFactory, attach an handler for the OnConnected event to update the UI. The SocketFactory’s Start method is queued on the thread pool to run async, this way the UI thread will remain responsive. The Leap Motion get’s initialized and we start a timer. This timer will make sure that every 200 milliseconds the coordinates of the ellipse are send over the socket to the client. The sending of the message needs to be done on the UI thread because we need the ellipse’s coordinates, and that ellipse lives on the UI thread.</p>  <p>Now, why use a timer? In the first version of this sample a message was send every time the ellipse moved, this resulted in really really really poor performance, messages were being send faster than they arrived causing all kinds of weird behavior. Sending it every 200 milliseconds makes it move quite well.</p>  <p>Everything is in place now, so run it and move the ellipse around with the Leap Motion!</p>  <h2>Conclusion</h2>  <p>In this post I’ve explained my adventure of connecting the Leap Motion to a Windows Phone application by using sockets. While not the easiest thing to set up or use, sockets are a really powerful way of communicating between applications no matter what platform they’re on (as long as that platform supports sockets).</p>  <p>The Leap Motion is a great device. It’s small, light, has a very small footprint on your system and is just plain fun to mess around with. I could’ve used anything for a socket example but making something move on screen, on two devices at the same time by just moving your hand has something magically. The Leap Motion is definitely on my list of awesome gadgets.</p>  <p>The code for this post can be found on my <a href="http://sdrv.ms/17grEfS" target="_blank">Skydrive</a></p>

This is an imported post. It was imported from my old blog using an automated tool and may contain formatting errors and/or broken images.

Leave a Comment