为什么我的队列总是空的?

时间:2018-04-16 11:33:48

标签: c# multithreading amazon-ec2 tcp queue

我正在使用Amazon AWS开发一个小型应用程序。我正在使用客户端/服务器架构。当我在同一个实例上运行客户端和服务器应用程序时,我没有问题,但是当我将服务器应用程序部署到另一个实例时,我遇到了麻烦。我打开了所有必需的端口并整理了冷壁等。客户端实例和服务器实例之间没有通信问题:客户端到服务器之间的消息完全到达,没有问题。

我的问题是,在我的客户端应用程序上,在另一个线程上的另一个类中填充的队列在网络上运行时始终为空。

客户端应用程序上的“CommunicationsManager”如下所示:

using System.Collections;
using System.Collections.Generic;
using Hazel;
using System;
using Hazel.Tcp;
using System.Net;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;

public class CommunicationsManager
{

    //public  Queue RawMessages = Queue.Synchronized(new Queue()); //Doesn't work either
    public Queue<byte[]> RawMessages = new Queue<byte[]>();

    public int Port;
    public bool RunLocally;
    public TcpConnection Connection { get; set; }

    public CommunicationsManager(int port)
    {
        Port = port;
    }

    public void Connect()
    {
        var ip = RunLocally ? "127.0.0.1" : "SOME REMOTE IP";
        NetworkEndPoint endPoint = new NetworkEndPoint(ip, Port);
        Connection = new TcpConnection(endPoint);
        Connection.DataReceived += DataReceived;
        Connection.Connect();
    }

    private void DataReceived(object sender, DataReceivedEventArgs args)
    {
        //This does fire and it does add to RawMessages
        RawMessages.Enqueue(args.Bytes);
        args.Recycle();
    }

    public void Disconnect()
    {
        if (Connection.State == ConnectionState.Connected)
        {
            Connection.Close();
        }
    }

    public void Send()
    {
        //Not implemented
    }

}

我有另一个名为“Client”的类,此对象检查消息是否已到达,如果是,则将其出列并进行处理。

using Hazel;
using Hazel.Tcp;
using NLog;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;

public class Client
{

    private CommunicationsManager CommunicationsManager;

    void Start()
    {
        CommunicationsManager = new CommunicationsManager();
        CommunicationsManager.RunLocally = RunLocally;
        CommunicationsManager.Port = Port;
        CommunicationsManager.Connect();

        Task.Factory.StartNew(() =>
        {
            while (true)
            {
                if (CommunicationsManager.RawMessages.Count > 0)
                {
                    // Always zero...
                }
                else
                {
                    Log.Debug("No message from server...");
                }
            }

        });
    }
}

出于某种原因,我的CommunicationsManager.RawMessages.Count始终为零。我已尝试使用ConcurrentBagConcurrentQueue,我尝试让线程读取此队列(在CommunicationsManager类中)并填充另一个队列并从该新队列中读取Client ,但似乎没有任何效果。

消息肯定已到达...... DataReceived事件触发,RawMessages队列确实包含数据。

最奇怪的是,当客户端和服务器应用程序是同一台机器时,这可以工作......如果我将服务器应用程序移动到另一个实例,它就不起作用。

有没有人有任何想法?

0 个答案:

没有答案