提案されたアーキテクチャを使用する際に注意すべき点がいくつかあります。
ソケット経由で HTTP リクエストを送信しようとしています
原則として、ソケットを使用して下位レベルで http をチャットすることはできますが、この方法での通信が失敗するケースが多数あることに注意する必要があります。これらのエラーは主に、ユーザーがブラウザでプロキシ サーバーを有効にしている場合に発生します。これは、ソケット経由で接続するときにプロキシを検出して使用する効果的な手段がないためです。
ポリシー サーバーを作成するには、TcpListenerクラスを使用できます。次のように聞き始めます。
var tcpListener = new TcpListener(IPAddress.Any, 843 );
tcpListener.start();
tcpListener.BeginAcceptTcpClient(new AsyncCallback(NewClientHandler), null);
メソッド NewClientHandler の形式は次のとおりです。
private void NewClientHandler(IAsyncResult ar)
{
TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar);
...
この時点で、tcpClient オブジェクトを独自に作成したクラスに提供して、ソケットからのデータの検証を処理することができます。これを RemoteClient と呼びます。
RemoteClient では、次のようになります。
var buffer=new byte[BUFFER_SIZE];
tcpClient.GetStream().BeginRead(buffer, 0, buffer.Length, Receive, null);
および Receive メソッド:
private void Receive(IAsyncResult ar)
{
int bytesRead;
try
{
bytesRead = tcpClient.GetStream().EndRead(ar);
}
catch (Exception e)
{
//something bad happened. Cleanup required
return;
}
if (bytesRead != 0)
{
char[] charBuffer = utf8Encoding.GetChars(buffer, 0, bytesRead);
try
{
tcpClient.GetStream().BeginRead(buffer, 0, buffer.Length, Receive, null);
}
catch (Exception e)
{
//something bad happened. Cleanup required
}
}
else
{
//socket closed, I think?
return;
}
}
およびいくつかの送信方法:
public void Send(XmlDocument doc)
{
Send(doc.OuterXml);
}
private void Send(String str)
{
Byte[] sendBuf = utf8Encoding.GetBytes(str);
Send(sendBuf);
}
private void Send(Byte[] sendBuf)
{
try
{
tcpClient.GetStream().Write(sendBuf, 0, sendBuf.Length);
tcpClient.GetStream().WriteByte(0);
tcpClient.GetStream().WriteByte(13); //very important to terminate XmlSocket data in this way, otherwise Flash can't read it.
}
catch (Exception e)
{
//something bad happened. cleanup?
return;
}
}
それが私が考えるすべての重要な詳細です。これは少し前に書きました... Receive メソッドは手直しが必要なように見えますが、始めるには十分なはずです。