我有这个非常基本的工作角色正在运行,监听传入的 TCP 连接并处理它们。但是由于某种原因,一段时间后现在失败了..似乎它不再接收数据...在跟踪中没有看到异常。现在让它同步......仍然是同样的问题。
这个想法是接受一个 HTTP 请求并给出一个 302 重定向。
当我通过端口 80 上的 telnet 连接到它时,它可以工作。
一旦我使用浏览器,它就会很快开始失败。
当我在端口 80 上再次尝试时,不再响应。
public class WorkerRole : RoleEntryPoint
{
public override void Run()
{
TcpListener server = null;
IPEndPoint ipin = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Server"].IPEndpoint;
server = new TcpListener(ipin);
server.ExclusiveAddressUse = false;
server.Start();
try
{
while (true)
{
TcpClient client = server.AcceptTcpClient();
HandleSyncConnection(client);
}
}
catch (Exception ex)
{
Trace.WriteLine("Server stopped. Exception:" + ex.Message);
return;
}
}
private void HandleSyncConnection(TcpClient client)
{
try
{
// Setup reader/writer
NetworkStream netStream = client.GetStream();
StreamReader reader = new StreamReader(netStream, Encoding.ASCII);
StreamWriter writer = new StreamWriter(netStream, Encoding.ASCII);
writer.AutoFlush = true;
byte[] baBuffer = new byte[10000];
byte[] baHeader = { 13, 10, 13, 10 };
Int32 iTotalBytesReceived = 0;
Int32 iHeaderFound = 0;
while (iTotalBytesReceived < baBuffer.Length)
{
Int32 iBytesReceived = netStream.Read(baBuffer, iTotalBytesReceived, baBuffer.Length - iTotalBytesReceived);
if (iBytesReceived == 0)
break;
for (int i = 0; i < iBytesReceived; i++)
{
if (baBuffer[iTotalBytesReceived + i] == baHeader[iHeaderFound])
iHeaderFound++;
else
iHeaderFound = 0;
}
iTotalBytesReceived += iBytesReceived;
if (iHeaderFound == baHeader.Length)
break;
Thread.Sleep(50);
}
String strResponse;
Trace.TraceInformation("Request received");
strResponse = "HTTP/1.1 302 Redirect" + EOL + "Location: http://www.google.com");
strResponse += EOL + "Content-Type: text/html" + EOL + "Cache-Control: no-cache" + EOL + "Connection: close" + EOL + "Content-Length: 0" + EOL + EOL;
writer.Write(strResponse);
writer.Close();
reader.Close();
// Done!
client.Close();
}
catch (Exception e)
{
Trace.TraceError("Server stopped in the handling of sync " + e.Message);
}
}
public override bool OnStart()
{
return base.OnStart();
}