WEBSITE

Silverlight Recipes : Using Sockets to Communicate over TCP (part 5) - The Policy Server

7/21/2012 11:38:08 AM
4.4. The Policy Server

The policy server is similarly implemented as a console program that listens on all available IP addresses, bound to a well-known port 943. Listing 7 shows the code for the policy server.

Listing 7. Implementation for the PolicyServer type in PolicyListener.cs
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Recipe7_5.PolicyServer
{

  internal class PolicyListener
  {
    Socket ListenerSocket { get; set; }
    SocketAsyncEventArgs sockEvtArgs = null;
    //valid policy request string
    public static string ValidPolicyRequest = "<policy-file-request/>";

    public PolicyListener()
    {
      //bind to all available addresses and port 943
      IPEndPoint ListenerEndPoint =
        new IPEndPoint(IPAddress.Any, 943);
      ListenerSocket =
        new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      ListenerSocket.Bind(ListenerEndPoint);
      ListenerSocket.Listen(20);
    }
    internal void ListenForPolicyRequest()
    {
      sockEvtArgs = new SocketAsyncEventArgs();
      sockEvtArgs.Completed += new EventHandler<SocketAsyncEventArgs>(
          delegate(object Sender, SocketAsyncEventArgs e)
          {
            //process this request
            ReadPolicyRequest(e.AcceptSocket);
            //go back to listening
            ListenForPolicyRequest();
          });
      ListenerSocket.AcceptAsync(sockEvtArgs);
    }
    private bool ReadPolicyRequest(Socket ClientSocket)
    {
      SocketAsyncEventArgs sockEvtArgs =
        new SocketAsyncEventArgs { UserToken = ClientSocket };
      sockEvtArgs.SetBuffer(
        new byte[ValidPolicyRequest.Length], 0, ValidPolicyRequest.Length);
      sockEvtArgs.Completed += new EventHandler<SocketAsyncEventArgs>(
          delegate(object Sender, SocketAsyncEventArgs e)
          {
            if (e.SocketError == SocketError.Success)
            {
              //get policy request string

					  

string PolicyRequest = new UTF8Encoding().
                GetString(e.Buffer, 0, e.BytesTransferred);
              //check for valid format
              if (PolicyRequest.CompareTo(ValidPolicyRequest) == 0)
                //valid request-send policy
                SendPolicy(e.UserToken as Socket);
            }
          });
      return ClientSocket.ReceiveAsync(sockEvtArgs);
    }
    private void SendPolicy(Socket ClientSocket)
    {
      //read the policy file
      FileStream fs = new FileStream("clientaccesspolicy.xml", FileMode.Open);
      byte[] PolicyBuffer = new byte[(int)fs.Length];
      fs.Read(PolicyBuffer, 0, (int)fs.Length);
      fs.Close();

      SocketAsyncEventArgs sockEvtArgs =
        new SocketAsyncEventArgs { UserToken = ClientSocket };
      //send the policy
      sockEvtArgs.SetBuffer(PolicyBuffer, 0, PolicyBuffer.Length);
      sockEvtArgs.Completed += new EventHandler<SocketAsyncEventArgs>(
          delegate(object Sender, SocketAsyncEventArgs e)
          {
            //close this connection
            if (e.SocketError == SocketError.Success)
              (e.UserToken as Socket).Close();
          });
      ClientSocket.SendAsync(sockEvtArgs);
    }
  }
}

					  

After a connection request is accepted by the policy server, it attempts to receive a policy request from the client and checks it for validity by comparing it to the string literal <policy-file-request/>. If valid, the policy file is read into memory and sent back to the client through the connected client socket. When the send is completed, the socket connection is closed, and the policy server keeps listening for more policy requests.

Other  
  •  Microsoft ASP.NET 3.5 : The HTTP Request Context - The global.asax File
  •  Microsoft ASP.NET 3.5 : The HTTP Request Context - Initialization of the Application
  •  Free Email Everywhere and Anytime
  •  IIS 7.0 : Managing Web Sites - Administrative Tasks - Limiting Web Site Usage, Configuring Web Site Logging and Failed Request Tracing
  •  IIS 7.0 : Managing Web Sites - Administrative Tasks - Adding a New Web Site
  •  IIS 7.0 : Managing Worker Processes and Requests
  •  Websocket: Internet In Real Time
  •  IIS 7.0 : Managing Application Pools (part 3) - Advanced Application Pool Configuration, Monitoring Application Pool Recycling Events
  •  IIS 7.0 : Managing Application Pools (part 2) - Managing Application Pool Identities
  •  IIS 7.0 : Managing Application Pools (part 1) - Application Pool Considerations, Adding a New Application Pool
  •  
    Top 10
    Review : Sigma 24mm f/1.4 DG HSM Art
    Review : Canon EF11-24mm f/4L USM
    Review : Creative Sound Blaster Roar 2
    Review : Philips Fidelio M2L
    Review : Alienware 17 - Dell's Alienware laptops
    Review Smartwatch : Wellograph
    Review : Xiaomi Redmi 2
    Extending LINQ to Objects : Writing a Single Element Operator (part 2) - Building the RandomElement Operator
    Extending LINQ to Objects : Writing a Single Element Operator (part 1) - Building Our Own Last Operator
    3 Tips for Maintaining Your Cell Phone Battery (part 2) - Discharge Smart, Use Smart
    REVIEW
    - First look: Apple Watch

    - 3 Tips for Maintaining Your Cell Phone Battery (part 1)

    - 3 Tips for Maintaining Your Cell Phone Battery (part 2)
    VIDEO TUTORIAL
    - How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 1)

    - How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 2)

    - How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 3)
    Popular Tags
    Video Tutorail Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Exchange Server Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe Photoshop CorelDRAW X5 CorelDraw 10 windows Phone 7 windows Phone 8 Iphone