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

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(经典 Cloud 服务)中,从日志中我可以看到我们正在接收不是由我们发起的连接 . 当我们尝试从流中读取时,这些连接导致“远程主机强制关闭连接”异常:

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

  • 有没有办法识别这些连接?目前,我已将代码包装在try / catch中,但我不确定这是否是最好的方法 .

任何建议将不胜感激!