Pushing Data to a Silverlight Client with Sockets: Part II

In Part 1 of this two part series on socket support in Silverlight 2 I discussed how a server could be created to listen for clients using classes in the System.Net.Sockets namespace.  In that post the TcpListener class was used to listen for client connections and the client stream was accessed using the TcpClient class's GetStream() method.  In this post I'll cover how a Silverlight client can connect to a server using sockets and receive data pushed by the server asynchronously.

Creating a Silverlight Socket Client

Silverlight 2 provides a Socket class located in the System.Net.Sockets namespace (a Silverlight namespace...not the .NET Framework namespace mentioned earlier) that can be used to connect a client to a server to send and/or receive data.  The Socket class works in conjunction with a SocketAsyncEventArgs class to connect and send/receive data.  The SocketAsyncEventArgs class is used to define asynchronous callback methods and pass user state between those methods (such as the Socket object that originally connected to the server).  An example of using the Socket and SocketAsyncEventArgs classes is shown next:

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    DnsEndPoint endPoint = new DnsEndPoint(Application.Current.Host.Source.DnsSafeHost, 4530);
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
    args.UserToken = socket;
    args.RemoteEndPoint = endPoint;
    args.Completed += new EventHandler<SocketAsyncEventArgs>(OnSocketConnectCompleted);
    socket.ConnectAsync(args);   
}


This code first identifies the application's host server along with a port of 4530 (Silverlight can only connect to servers on a port between 4502 and 4532).  A Socket object capable of communicating using the TCP protocol is then created.  Once the Socket object is created, a SocketAsyncEventArgs object is instantiated and the socket object is assigned to the UserToken property so that it is passed through to other methods.  The target endpoint of the server is set using the RemoteEndPoint property and the argument object's Completed event is hooked to an asynchronous callback method named OnSocketConnectCompleted.  Once these objects are created and ready to use, the Socket object's ConnectAsync() method can be called which accepts a SocketAsyncEventArgs object as a parameter.

When the client is connected to the server the following method is called which creates a buffer to hold data received from the server and rewires the SocketAsyncEventArgs's Completed event to a different callback method named OnSocketReceive:

private void OnSocketConnectCompleted(object sender, SocketAsyncEventArgs e)
{
    byte[] response = new byte[1024];
    e.SetBuffer(response, 0, response.Length);
    e.Completed -= new EventHandler<SocketAsyncEventArgs>(OnSocketConnectCompleted);
    e.Completed += new EventHandler<SocketAsyncEventArgs>(OnSocketReceive);
    Socket socket = (Socket)e.UserToken;
    socket.ReceiveAsync(e);
}


The Socket object's ReceiveAsync() method is then called to begin the process of accepting data from the server.  As data is received the OnSocketReceive() method is called which handles deserializing XML data returned from the server into CLR objects that can be used in the Silverlight client. 

private void OnSocketReceive(object sender, SocketAsyncEventArgs e)
{
    StringReader sr = null;
    try
    {
        string data = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
        sr = new StringReader(data);
        //Get initial team data
        if (_Teams == null && data.Contains("Teams"))
        {
            XmlSerializer xs = new XmlSerializer(typeof(Teams));
            _Teams = (Teams)xs.Deserialize(sr);
            this.Dispatcher.BeginInvoke(UpdateBoard);
        }

        //Get updated score data
        if (data.Contains("ScoreData"))
        {
            XmlSerializer xs = new XmlSerializer(typeof(ScoreData));
            ScoreData scoreData = (ScoreData)xs.Deserialize(sr);
            ScoreDataHandler handler = new ScoreDataHandler(UpdateScoreData);
            this.Dispatcher.BeginInvoke(handler, new object[] { scoreData });
        }
    }
    catch { }
    finally
    {
        if (sr != null) sr.Close();
    }
    //Prepare to receive more data
    Socket socket = (Socket)e.UserToken;
    socket.ReceiveAsync(e);
}


The deserialization process is handled by the XmlSerializer class which keeps the code nice and clean.  Alternatively, the XmlReader class could be used or the LINQ to XML technology that's available in Silverlight.  Notice that data is routed back to the UI thread by using the Dispatcher class's BeginInvoke() method.  If you've worked with Windows Forms before then this should look somewhat familiar.  That's all there is to work with sockets in a Silverlight client.  There's certainly some work involved, but many of the complexities are hidden away in the Socket and SocketAsyncEventArgs classes which both minimize the need to work with threads directly.  I've already shown what the client interface looks like as data is updated but here it is one more time (click the image to see an animated gif of the application in action):

The complete code for the Silverlight client and server application can be downloaded here.

comments powered by Disqus

4 Comments

Comments have been disabled for this content.