使用您建议的架构需要注意的一些事项:
尝试通过套接字发送 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);
和一个接收方法:
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 方法看起来可以通过返工来完成,但它应该足以让你开始。