西西軟件園多重安全檢測下載網(wǎng)站、值得信賴的軟件下載站!
軟件
軟件
文章
搜索

首頁編程開發(fā)C#.NET → 模擬IIS向Silverlight輸出策略文件

模擬IIS向Silverlight輸出策略文件

前往專題相關(guān)軟件相關(guān)文章發(fā)表評論 來源:本站整理時間:2010/9/13 23:33:32字體大。A-A+

作者:佚名點擊:152次評論:0次標(biāo)簽: IIS Silverlight

  • 類型:站長工具大。92KB語言:中文 評分:5.0
  • 標(biāo)簽:
立即下載

最近的Silverlight開發(fā)中,由于部分需求對實時性和數(shù)據(jù)量下載速度有要求,部分WCF服務(wù)配置成了netTcpBinding,這種方式跟普通的service.svc寄宿IIS不同的是,Silverlight需要的策略文件需要放置在本機(jī)IIS的根下,也就是wwwroot文件夾下,以滿足Silverlight在以TCP協(xié)議調(diào)用本機(jī)WCF服務(wù)時請求策略文件。

(注:Silverlight通過TCP協(xié)議調(diào)用WCF服務(wù)時,會以http方式請求主機(jī)的一個策略文件,地址是http://localhost/clientaccesspolicy.xml)

這其實是個不太好的選擇,程序運(yùn)行的所需的環(huán)境被分成了兩部分,同事的機(jī)器上并未安裝IIS,為了大家開發(fā)簡便,不用在額外安裝IIS,也為了讓程序更加獨立,我就想能不能寫代碼監(jiān)控80端口模擬IIS向Silverlight輸出這個策略文件。

解決方法

有了這個想法之后,首先想到的是通過Socket進(jìn)行監(jiān)聽,因為此前在MSDN上看到過這種方式,但很無奈,將代碼轉(zhuǎn)移過來之后,并未成功。相信做過Silverlight在Socket方面應(yīng)用的朋友對下面這個PolicyServer類很熟悉吧。

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace PolicyServer
{
// Encapsulate and manage state for a single connection from a client
class PolicyConnection
{
    private Socket m_connection;

    // buffer to receive the request from the client
    private byte[] m_buffer;
    private int m_received;

    // the policy to return to the client
    private byte[] m_policy;

    // the request that we're expecting from the client
    private static string s_policyRequestString = "<policy-file-request/>";



    public PolicyConnection(Socket client, byte[] policy)
    {
        m_connection = client;
        m_policy = policy;

        m_buffer = new byte[s_policyRequestString.Length];
        m_received = 0;

        try
        {
            // receive the request from the client
            m_connection.BeginReceive(m_buffer, 0, s_policyRequestString.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
        }
        catch (SocketException)
        {
            m_connection.Close();
        }
    }

    // Called when we receive data from the client
    private void OnReceive(IAsyncResult res)
    {
        try
        {
            m_received += m_connection.EndReceive(res);

            // if we haven't gotten enough for a full request yet, receive again
            if (m_received < s_policyRequestString.Length)
            {
                m_connection.BeginReceive(m_buffer, m_received, s_policyRequestString.Length - m_received, SocketFlags.None, new AsyncCallback(OnReceive), null);
                return;
            }

            // make sure the request is valid
            string request = System.Text.Encoding.UTF8.GetString(m_buffer, 0, m_received);
            if (StringComparer.InvariantCultureIgnoreCase.Compare(request, s_policyRequestString) != 0)
            {
                m_connection.Close();
                return;
            }

            // send the policy
            m_connection.BeginSend(m_policy, 0, m_policy.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
        }
        catch (SocketException)
        {
            m_connection.Close();
        }
    }

    // called after sending the policy to the client; close the connection.
    public void OnSend(IAsyncResult res)
    {
        try
        {
            m_connection.EndSend(res);
        }
        finally
        {
            m_connection.Close();
        }
    }
}

// Listens for connections on port 943 and dispatches requests to a PolicyConnection
class PolicyServer
{
    private Socket m_listener;
    private byte[] m_policy;

    // pass in the path of an XML file containing the socket policy
    public PolicyServer(string policyFile)
    {
        // Load the policy file
        FileStream policyStream = new FileStream(policyFile, FileMode.Open);

        m_policy = new byte[policyStream.Length];
        policyStream.Read(m_policy, 0, m_policy.Length);

        policyStream.Close();

        m_listener = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);

        m_listener.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0);

        m_listener.Bind(new IPEndPoint(IPAddress.IPv6Any, 943));
        m_listener.Listen(10);

        m_listener.BeginAccept(new AsyncCallback(OnConnection), null);
    }

     public void OnConnection(IAsyncResult res)
    {
        Socket client = null;

        try
        {
            client = m_listener.EndAccept(res);
        }
        catch (SocketException)
        {
            return;
        }

        // handle this policy request with a PolicyConnection
        PolicyConnection pc = new PolicyConnection(client, m_policy);

        // look for more connections
        m_listener.BeginAccept(new AsyncCallback(OnConnection), null);
    }

    public void Close()
    {
        m_listener.Close();
    }
}
public class Program
{
    static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            Console.WriteLine("usage: PolicyServer.exe PolicyFile.xml");
            return;
        }

        PolicyServer ps = new PolicyServer(args[0]);
        System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
    }
}
}
  此路不通之后,又想起使用HttpListener類,看看是否能夠監(jiān)聽http請求,果然能夠截獲HTTP的請求 HttpListener listener = new HttpListener(); listener.Prefixes.Add(http://localhost/); listener.Start();Console.WriteLine("開始監(jiān)聽…"); HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; 但是這種方式有個明顯的缺點,就是線程是阻塞的。于是,又想到使用線程池。 System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(Listen)); private static void Listen(object state) { while (httpListener.IsListening) { httpListener.BeginGetContext(new AsyncCallback(ListenerCallback), httpListener); listenForNextRequest.WaitOne(); } }

這樣的話,每接收一個請求便會異步處理這個請求。在請求的處理上,接收請求后需要向外輸出策略文件流,供silverlight端接收驗證。

using(System.Net.HttpListenerResponse response = context.Response)

{ System.Threading.Thread.Sleep(1000); string responseString = "<?xml version=\"1.0\" encoding=\"utf-8\"?> " + " <access-policy> " + " <cross-domain-access> " + " <policy> " + " <allow-from http-request-headers=\"*\">" + " <domain uri=\"*\" /> " + " </allow-from> " + " <grant-to> " + " <socket-resource port=\"4502-4534\" protocol=\"tcp\" /> " + " </grant-to> " + " </policy> " + " </cross-domain-access>" + " </access-policy>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.LongLength; response.OutputStream.Write(buffer, 0, buffer.Length); }

啟動這個模擬服務(wù),將clientaccesspolicy從wwwroot中移除后再運(yùn)行一下程序,OK,我們不再需要將策略文件放到IIS下了。

注意:如果你的機(jī)器裝了IIS,請還是放一個策略文件到wwwroot吧,否則就停掉IIS再使用這個類,因為IIS和這個類只能有一方監(jiān)聽80端口。

    相關(guān)評論

    閱讀本文后您有什么感想? 已有人給出評價!

    • 8 喜歡喜歡
    • 3 頂
    • 1 難過難過
    • 5 囧
    • 3 圍觀圍觀
    • 2 無聊無聊

    熱門評論

    最新評論

    發(fā)表評論 查看所有評論(0)

    昵稱:
    表情: 高興 可 汗 我不要 害羞 好 下下下 送花 屎 親親
    字?jǐn)?shù): 0/500 (您的評論需要經(jīng)過審核才能顯示)