如果您嘗試在端口範圍4502-4534中建立TCP連接,Silverlight將首先在端口943上發佈請求以檢索客戶端訪問策略文件內容 - 它不會讀取http://localhost.myserivce.com/clientaccesspolicy.xml處的文件,因爲這是僅用於HTTP請求。 您需要將服務器配置爲偵聽TCP端口943,期望請求字符串等於<policy-file-request/>
並回復xml文件內容。
下面的代碼顯示了一個基本的實現,您需要使用端口943來傳遞給本地IPEndPoint:
public class SocketPolicyServer
{
private const string m_policyRequestString = "<policy-file-request/>";
private string m_policyResponseString;
private TcpListener m_listener;
bool _started = false;
public SocketPolicyServer()
{
m_policyResponseString = File.ReadAllText("path/to/clientaccesspolicy.xml");
}
public void Start(IPEndPoint endpoint)
{
m_listener = new TcpListener(endpoint);
m_listener.Start();
_started = true;
m_listener.BeginAcceptTcpClient(HandleClient, null);
}
public event EventHandler ClientConnected;
public event EventHandler ClientDisconnected;
private void HandleClient(IAsyncResult res)
{
if(_started)
{
try
{
TcpClient client = m_listener.EndAcceptTcpClient(res);
m_listener.BeginAcceptTcpClient(HandleClient, null);
this.ProcessClient(client);
}
catch(Exception ex)
{
Trace.TraceError("SocketPolicyServer : {0}", ex.Message);
}
}
}
public void Stop()
{
_started = false;
m_listener.Stop();
}
public void ProcessClient(TcpClient client)
{
try
{
if(this.ClientConnected != null)
this.ClientConnected(this, EventArgs.Empty);
StreamReader reader = new StreamReader(client.GetStream(), Encoding.UTF8);
char[] buffer = new char[m_policyRequestString.Length];
int read = reader.Read(buffer, 0, buffer.Length);
if(read == buffer.Length)
{
string request = new string(buffer);
if(StringComparer.InvariantCultureIgnoreCase.Compare(request, m_policyRequestString) == 0)
{
StreamWriter writer = new StreamWriter(client.GetStream());
writer.Write(m_policyResponseString);
writer.Flush();
}
}
}
catch(Exception ex)
{
Trace.TraceError("SocketPolicyServer : {0}", ex.Message);
}
finally
{
client.GetStream().Close();
client.Close();
if(this.ClientDisconnected != null)
this.ClientDisconnected(this, EventArgs.Empty);
}
}
}