1

我编写了一个 Azure Worker Role,它设置了一个 TCPListener 并接收消息。这些消息然后根据其内容被路由到不同的服务总线队列。工人角色代码如下:

private async Task RunAsync(CancellationToken cancellationToken)
{
    TcpListener listener;
    IPEndPoint ipEndPoint;

    ipEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["MainEndpoint"].IPEndpoint;
    listener = new TcpListener(ipEndPoint) { ExclusiveAddressUse = false };
    listener.Start();

    _log.Info($"Created and started listener on {ipEndPoint.Address}:{ipEndPoint.Port}");

    while (!cancellationToken.IsCancellationRequested)
    {
        listener.BeginAcceptTcpClient(AsyncMessageHandler, listener);
        _connectionWaitHandle.WaitOne();
    }
}

private void AsyncMessageHandler(IAsyncResult result)
{
    byte[] bytes = new byte[0];
    try
    {
        _log.Debug("Session initiated");

        var listener = (TcpListener)result.AsyncState;
        var client = listener.EndAcceptTcpClient(result);

        _connectionWaitHandle.Set();

        var netStream = client.GetStream();
        bytes = new byte[short.MaxValue];
        netStream.Read(bytes, 0, bytes.Length);
        client.Close();
    }
    catch (Exception ex)
    {
        _log.Warn("An error occurred receiving a message", ex);
    }

    // Do stuff with message
}

在我的开发机器上,一切都按预期工作;当我使用控制台应用程序发送消息时正在接收消息,并且没有收到其他消息。

然而,在 Azure(经典云服务)中,从日志中我可以看到我们正在接收不是由我们发起的连接。当我们尝试从流中读取时,这些连接会导致“连接被远程主机强制关闭”异常:

netStream.Read(bytes, 0, bytes.Length);
  • 是否可能是 Azure 体系结构中正在监视服务以确保它正在侦听 Endpoint 配置中配置的端口?

  • 有什么方法可以识别这些联系吗?目前,我已将代码包装在 try/catch 中,但我不确定这是否是最好的方法。

任何建议将不胜感激!

4

0 回答 0