1

我正在尝试使用 netmq(zeroMQ 的端口)。这是我发现的问题。这是一个代码:

class Program
{
    private static NetMQContext context;

    static void Main(string[] args)
    {
        context = NetMQContext.Create();
        using (var puller = context.CreatePullSocket())
        {
            puller.Bind("tcp://127.0.0.1:5651");
            Thread.Sleep(500);
            for (int i = 0; i < 5; i++)
            {
                Task.Run(new Action(PusheThread));
            }
            Console.WriteLine("any key to start receive");
            Console.ReadKey();
            Msg msg = new Msg();
            msg.InitEmpty();
            for (; puller.TryReceive(ref msg, new TimeSpan(0, 0, 5)); msg = new Msg(), msg.InitEmpty())
            {
                var s = Encoding.UTF8.GetString(msg.Data);
                Console.WriteLine(s);
            }
        }
        Console.WriteLine("any");
        Console.ReadKey();
    }

    static void PusheThread()
    {
        var guid = Guid.NewGuid();
        Console.WriteLine("started: " + guid);
        using (var pusher = context.CreatePushSocket())
        {
            pusher.Connect("tcp://127.0.0.1:5651");
            for (int i = 0; i < 5; i++)
            {
                pusher.Send("helo! " + guid);
            }
        }
    }
}

如果我们运行此代码并在控制台中观察,我们会看到一些消息丢失了。喜欢:

any key to start receive
started: 8aeca8e5-ed41-4055-ab72-750a0e61a680
started: 4211d77a-ad9f-40f1-9382-121156325128
started: bd735e75-2692-4abe-b8b1-fbddbe21e546
started: 6749d3bb-6b2b-4caa-b22e-755dba4d932d
started: 281ff59e-4430-4fc6-9435-4dc2c5e6015e
helo! 8aeca8e5-ed41-4055-ab72-750a0e61a680
helo! 6749d3bb-6b2b-4caa-b22e-755dba4d932d
helo! 8aeca8e5-ed41-4055-ab72-750a0e61a680
helo! 6749d3bb-6b2b-4caa-b22e-755dba4d932d
helo! 8aeca8e5-ed41-4055-ab72-750a0e61a680
helo! 6749d3bb-6b2b-4caa-b22e-755dba4d932d
helo! 8aeca8e5-ed41-4055-ab72-750a0e61a680
helo! 6749d3bb-6b2b-4caa-b22e-755dba4d932d
helo! 8aeca8e5-ed41-4055-ab72-750a0e61a680
helo! 6749d3bb-6b2b-4caa-b22e-755dba4d932d
any

正如我们所见,哪里没有来自 的消息4211d77a-ad9f-40f1-9382-121156325128bd735e75-2692-4abe-b8b1-fbddbe21e546还有另一个消息。是多线程的问题吗?还是我做错了什么?谢谢。

4

1 回答 1

0

问题在于PusheThread你简单地杀死新创建PushSocket的快速。

static void PusheThread()
{
    var guid = Guid.NewGuid();
    Console.WriteLine("started: " + guid);
    using (var pusher = context.CreatePushSocket())
    {
        pusher.Connect("tcp://127.0.0.1:5651");
        for (int i = 0; i < 5; i++)
        {
            pusher.Send("helo! " + guid);
        }
        Thread.Sleep(5000);
    }
}

尽管这不是一个可靠的解决方案,但它应该证明问题是在能够发送消息之前PushSocket由语句处理的。using

有些消息甚至只是显示了 NetMQ 和 ZeroMQ 的速度有多快 :)

于 2015-07-17T06:50:30.060 回答