public static string Request(string input) { // prepare Socket var nanoSock = new NanomsgSocket(Domain.SP, Protocol.REQ); string result = null; bool messageReceived = false; // prepare Listener var listener = new NanomsgListener(); listener.ReceivedMessage += (sockedId) => { using (NanomsgReadStream inStream = nanoSock.ReceiveStream()) using (var unpacker = Unpacker.Create(inStream)) { string output; if (!unpacker.ReadString(out output)) throw new Exception("REP invalid"); result = output; } messageReceived = true; }; // Connect and Send Request listener.AddSocket(nanoSock); nanoSock.Connect("tcp://127.0.0.1:" + reqPort); using (NanomsgWriteStream outStream = nanoSock.CreateSendStream()) using(var packer = Packer.Create(outStream)) { packer.PackString(input); nanoSock.SendStream(outStream); } var start = DateTime.Now; while (!messageReceived && start + TimeSpan.FromSeconds(30) > DateTime.Now) { listener.Listen(TimeSpan.FromMilliseconds(250)); } listener.RemoveSocket(nanoSock); nanoSock.Dispose(); if (!messageReceived) { throw new Exception("REQ timed out"); } return result; }
public static void RunWorker(CancellationTokenSource cancellor, int workerId) { var serverThread = new Thread(() => { var nanoSock = new NanomsgSocket(Domain.SP, Protocol.REP); var nanoListener = new NanomsgListener(); nanoListener.ReceivedMessage += (socketId) => { string input; using (NanomsgReadStream inStream = nanoSock.ReceiveStream()) using (var unpacker = Unpacker.Create(inStream)) { if (!unpacker.ReadString(out input)) throw new Exception("REQ invalid"); Console.WriteLine(input); } using (NanomsgWriteStream outStream = nanoSock.CreateSendStream()) using (var packer = Packer.Create(outStream)) { packer.PackString("Hello " + input); nanoSock.SendStream(outStream); } }; nanoListener.AddSocket(nanoSock); nanoSock.Connect("tcp://127.0.0.1:" + repPort); while (!cancellor.IsCancellationRequested) { nanoListener.Listen(TimeSpan.FromMilliseconds(250)); } nanoListener.RemoveSocket(nanoSock); nanoSock.Dispose(); }); serverThread.Start(); serverThread.Join(TimeSpan.FromMilliseconds(40)); }