我在客户端有一个 RequestSocket 向服务器发送请求。服务器必须能够并行处理请求,所以我使用了带有轮询器的 RouterSocket。
我不确定这是否是最好的实现,因为它使用了大量的 CPU,而没有请求处理?具体来说,RouterSocket 上的 SendReady 事件非常频繁地触发。
class Program
{
static ConcurrentQueue<NetMQMessage> outgoingQueue = new ConcurrentQueue<NetMQMessage>();
static void Main(string[] args)
{
var poller = new Poller();
using (var context = NetMQContext.Create())
using (var router = context.CreateRouterSocket())
{
router.Bind("tcp://127.0.0.1:1337");
poller.AddSocket(router);
router.ReceiveReady += (s, a) => HandleRequest(a.Socket.ReceiveMessage());
router.SendReady += (s, a) =>
{
if (!outgoingQueue.IsEmpty)
{
NetMQMessage msg;
if (outgoingQueue.TryDequeue(out msg))
{
a.Socket.SendMessage(msg);
Console.WriteLine("Sent: " + msg[2].ConvertToString());
}
}
};
poller.Start();
}
}
static void HandleRequest(NetMQMessage requestMsg)
{
Console.WriteLine("Received: " + requestMsg[2].ConvertToString());
Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
NetMQMessage responseMsg = new NetMQMessage();
responseMsg.Append(requestMsg[0]);
responseMsg.AppendEmptyFrame();
responseMsg.Append("Enjoy " + requestMsg[2].ConvertToString());
outgoingQueue.Enqueue(responseMsg);
});
}
}