dan*_*dan 0 c# flash policy actionscript-3
如何在C#中创建套接字策略文件服务器.它所要做的就是在端口843上侦听字符串"<policy-file-request />",后跟一个NULL字节,然后返回一个XML字符串(这是套接字策略文件).
我之前没有编过这种东西,也不确定从哪里开始.我是否在Windows服务中创建它?欢迎任何提示或链接.
背景:
要从Flash联系Web服务,我使用'as3httpclient'库而不是URLRequest/URLLoader.这是因为它使我能够使用GET请求发送自定义标头.这个库使用低级套接字来完成它的工作.
当flash使用低级套接字连接到服务器时,它会查找套接字策略文件 - 这需要由套接字策略文件服务器提供.
使用建议的架构需要注意的一些事项:
原则上,您需要注意即使您可以使用套接字在较低级别聊天http,但是存在大量以这种方式进行通信的情况.如果用户在其浏览器中启用了代理服务器,则主要会发生这些故障,因为在通过套接字连接时没有有效的方法来发现并随后使用代理.
要创建策略服务器,可以使用TcpListener类.你会开始听如下:
var tcpListener = new TcpListener(IPAddress.Any, 843 );
tcpListener.start();
tcpListener.BeginAcceptTcpClient(new AsyncCallback(NewClientHandler), null);
Run Code Online (Sandbox Code Playgroud)
NewClientHandler方法将具有以下形式:
private void NewClientHandler(IAsyncResult ar)
{
TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar);
...
Run Code Online (Sandbox Code Playgroud)
此时,您可能希望将tcpClient对象提供给您自己创建的类,以处理来自套接字的数据的验证.我打算把它叫做RemoteClient.
在RemoteClient中,你会有这样的事情:
var buffer=new byte[BUFFER_SIZE];
tcpClient.GetStream().BeginRead(buffer, 0, buffer.Length, Receive, null);
Run Code Online (Sandbox Code Playgroud)
和接收方法:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
和一些发送方法:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我认为的所有重要细节.我前段时间写过这篇文章......接收方法看起来可以做返工,但它应该足以让你入门.