本文整理汇总了C#中NetMQMessage.Push方法的典型用法代码示例。如果您正苦于以下问题:C# NetMQMessage.Push方法的具体用法?C# NetMQMessage.Push怎么用?C# NetMQMessage.Push使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类NetMQMessage
的用法示例。
在下文中一共展示了NetMQMessage.Push方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SaveMessage_ReplyMessage_SholdCreateNewFileWithGuidAsName
public void SaveMessage_ReplyMessage_SholdCreateNewFileWithGuidAsName ()
{
var sut = new TitanicFileIO (Path.GetTempPath ());
var message = new NetMQMessage ();
message.Push ("Hello World");
message.Push ("echo");
var messageSize = message[0].BufferSize + message[1].BufferSize + 4; // 2 lines with \r\n
var id = Guid.NewGuid ();
sut.SaveMessage (TitanicOperation.Reply, id, message);
var expectedDir = sut.TitanicDirectory;
var expectedFile = Path.Combine (expectedDir, id + _reply_ending);
File.Exists (expectedFile).Should ().BeTrue ("because the file exists");
var info = new FileInfo (expectedFile);
info.Length.Should ().Be (messageSize);
File.Delete (expectedFile);
}
示例2: ReceiveImplicitConnect_ValidScenario_ShouldReturnRequest
public void ReceiveImplicitConnect_ValidScenario_ShouldReturnRequest()
{
const string hostAddress = "tcp://localhost:5557";
var loggingMessages = new List<string> ();
// setup the counter socket for communication
using (var context = NetMQContext.Create ())
using (var broker = context.CreateRouterSocket ())
using (var poller = new Poller ())
using (var session = new MDPWorker (hostAddress, "test", new[] { (byte) '1' }))
{
broker.Bind (hostAddress);
// we need to pick up any message in order to avoid errors
broker.ReceiveReady += (s, e) =>
{
var msg = e.Socket.ReceiveMultipartMessage ();
// we expect to receive a 5 Frame message
// [WORKER ADR][EMPTY]["MDPW01"]["READY"]["test"]
if (msg.FrameCount != 5)
Assert.Fail ("Message with wrong count of frames {0}", msg.FrameCount);
// make sure the frames are as expected
Assert.That (msg[1], Is.EqualTo (NetMQFrame.Empty));
Assert.That (msg[2].ConvertToString (), Is.EqualTo ("MDPW01"));
Assert.That (msg[3].BufferSize, Is.EqualTo (1));
Assert.That (msg[3].Buffer[0], Is.EqualTo ((byte) MDPCommand.Ready));
Assert.That (msg[4].ConvertToString (), Is.EqualTo ("test"));
// tell worker to stop gracefully
var reply = new NetMQMessage ();
reply.Push (new[] { (byte) MDPCommand.Kill });
// push MDP Version
reply.Push (msg[2]);
// push separator
reply.Push (NetMQFrame.Empty);
// push worker address
reply.Push (msg[0]);
// send reply which is a request for the worker
e.Socket.SendMessage (reply);
};
poller.AddSocket (broker);
Task.Factory.StartNew (poller.PollTillCancelled);
// set the event handler to receive the logging messages
session.LogInfoReady += (s, e) => loggingMessages.Add (e.Info);
// initialise the worker - broker protocol
session.Receive (null);
poller.CancelAndJoin ();
poller.RemoveSocket (broker);
Assert.That (loggingMessages.Count, Is.EqualTo (5));
Assert.That (loggingMessages[0], Is.EqualTo ("[WORKER] connected to broker at tcp://localhost:5557"));
Assert.That (loggingMessages[1].Contains ("[WORKER] sending"), Is.True);
Assert.That (loggingMessages[2].Contains ("[WORKER] received"));
Assert.That (loggingMessages[4].Contains ("abandoning"));
}
}
示例3: Request_ValidRequestStringGeneric_ShouldReturnExpectedGuid
public void Request_ValidRequestStringGeneric_ShouldReturnExpectedGuid ()
{
var expectedId = Guid.NewGuid ();
var replyMessage = new NetMQMessage ();
replyMessage.Push (expectedId.ToString ());
replyMessage.Push (TitanicReturnCode.Ok.ToString ());
var fakeMDPClient = new MDPTestClientForTitanicClient { ReplyMessage = replyMessage, RequestId = expectedId };
var generic = new TestEntity ();
var sut = new TitanicClient (fakeMDPClient);
var id = sut.Request ("echo", generic.ConvertToBytes ());
id.Should ().Be (expectedId.ToString ());
}
示例4: Request_ValidRequestStringBytes_ShouldReturnExpectedGuid
public void Request_ValidRequestStringBytes_ShouldReturnExpectedGuid ()
{
var expectedId = Guid.NewGuid ();
var replyMessage = new NetMQMessage ();
replyMessage.Push (expectedId.ToString ());
replyMessage.Push (TitanicReturnCode.Ok.ToString ());
var fakeMDPClient = new MDPTestClientForTitanicClient { ReplyMessage = replyMessage, RequestId = expectedId };
var sut = new TitanicClient (fakeMDPClient);
var id = sut.Request ("echo", Encoding.UTF8.GetBytes ("Hello World!"));
id.Should ().Be (expectedId.ToString ());
}
示例5: Send
public NetMQMessage Send (string serviceName, NetMQMessage request)
{
// first call is [mmi.service][servicename]
// return is [Ok]
// second call is [service][request]
// return is [reply]
m_count++;
if (m_count == 1)
{
// proceed only if commanded to -> is automatically called by TitanicBroker.Run
// and askes for a reply from a service, so wait until we want an answer
waitHandle.WaitOne ();
var reply = new NetMQMessage ();
reply.Push (MmiCode.Ok.ToString ());
return reply;
}
// wait to proceed until signaled
waitHandle.WaitOne ();
return request; // as echo service :-)
}
示例6: Send
public Task Send(ArraySegment<byte> data, params object[] connectionIDs)
{
var task = new Task(() =>
{
var msg = new NetMQMessage();
if (_socket is RouterSocket)
{
msg.Append(new byte[0]);
msg.AppendEmptyFrame();
}
msg.Append(data.Count == data.Array.Length ? data.Array : data.ToArray());
if (connectionIDs.Length <= 0)
_socket.SendMultipartMessage(msg);
else
{
foreach (var connection in connectionIDs)
{
if (_socket is RouterSocket && connection is byte[])
{
msg.Pop();
msg.Push(((byte[])connection));
}
_socket.SendMultipartMessage(msg);
}
}
});
task.Start(_scheduler);
return task;
}
示例7: Run
public void Run()
{
var rnd = new Random(m_id);
using (var context = NetMQContext.Create())
using (var worker = context.CreateRequestSocket())
{
worker.Connect(m_localBackendAddress);
Console.WriteLine("[WORKER {0}] Connected & READY", m_id);
// build READY message
var msg = new NetMQMessage();
var ready = NetMQFrame.Copy(new[] { Program.WorkerReady });
msg.Append(ready);
msg.Push(NetMQFrame.Empty);
msg.Push(new[] { m_id });
// and send to broker
worker.SendMessage(msg);
while (true)
{
// wait for a request - the REQ might be from a local client or a cloud request
var request = worker.ReceiveMessage();
if (request.FrameCount < 3)
{
Console.WriteLine("[WORKER {0}] ERR - received an empty message", m_id);
break; // something went wrong -> exit
}
Console.WriteLine("[WORKER {0}] received", m_id);
foreach (var frame in request)
Console.WriteLine("\t[{0}", frame.ConvertToString());
// simulate working for an arbitrary time < 2s
Thread.Sleep(rnd.Next(2000));
// simply send back what we received
worker.SendMessage(request);
}
}
}
示例8: CloseRequest_MaxEntryClosedAndAdditionalRequestsAndReplies_ShouldReorganizeQueue
public void CloseRequest_MaxEntryClosedAndAdditionalRequestsAndReplies_ShouldReorganizeQueue()
{
const int max_entries = 20;
const int additional_requests = 5;
var path = Path.Combine (Path.GetTempPath (), ".titanic", "Close_4");
var sut = new TitanicFileIO (path, max_entries);
var titanicQueue = sut.TitanicQueue;
for (var i = 0; i < max_entries + additional_requests; i++)
{
var id = Guid.NewGuid ();
sut.SaveNewRequestEntry (id); // -> fill titanic.queue
var message = new NetMQMessage ();
message.Push (string.Format ("Message #{0}", i));
message.Push ("echo");
sut.SaveMessage (TitanicOperation.Request, id, message);
}
foreach (var entry in sut.GetRequestEntries (null).Skip (3).Take (5))
{
sut.SaveProcessedRequestEntry (entry);
var message = sut.GetMessage (TitanicOperation.Request, entry.RequestId);
sut.SaveMessage (TitanicOperation.Reply, entry.RequestId, message);
}
var requests = sut.GetRequestEntries (null).ToArray ();
requests.Length.Should ().Be (max_entries + additional_requests);
requests.Count (re => re.State == RequestEntry.Is_Processed).Should ().Be (5);
for (var i = 0; i < max_entries; i++)
sut.CloseRequest (requests[i].RequestId); // mark closed not worrying about state
sut.GetNotClosedRequestEntries ()
.Count ()
.Should ()
.Be (additional_requests, "because 5 requests should have been left over!");
Directory.Delete (sut.TitanicDirectory, true);
}
示例9: ExistsMessage_ExistingMessageWrongState_ShouldUpdateCorrectRequestEntry
public void ExistsMessage_ExistingMessageWrongState_ShouldUpdateCorrectRequestEntry()
{
const int id_to_retrieve = 7;
var sut = new TitanicMemoryIO ();
var ids = new Guid[10];
for (var i = 0; i < 10; i++)
{
ids[i] = Guid.NewGuid ();
var request = new NetMQMessage ();
request.Push (string.Format ("Request #{0}", i));
request.Push ("echo");
sut.SaveMessage (TitanicOperation.Request, ids[i], request);
}
sut.ExistsMessage (TitanicOperation.Reply, ids[id_to_retrieve]).Should ().BeFalse ();
}
示例10: Send
// messages can be:
//
// REQUEST:
// in goes -> [service name][request]
// returns -> [return code][Guid]
// REPLY
// in goes -> [request id]
// returns -> [return code][reply]
// CLOSE
// in goes -> [request id]
//
public NetMQMessage Send (string serviceName, NetMQMessage message)
{
Log ($"requested service <{serviceName}> with request <{message}>");
if (ReplyMessage != null)
return new NetMQMessage (ReplyMessage); // to keep it intact for multiple tries return a copy(!)
var operation = (TitanicOperation) Enum.Parse (typeof (TitanicOperation), serviceName);
var reply = new NetMQMessage ();
switch (operation)
{
case TitanicOperation.Request:
var id = RequestId == Guid.Empty ? Guid.NewGuid () : RequestId;
reply.Push (id.ToString ());
reply.Push (TitanicReturnCode.Ok.ToString ());
break;
case TitanicOperation.Reply:
if (ReplyMessage == null)
{
reply.Push (ReplyDataFrame);
reply.Push (TitanicReturnCode.Ok.ToString ());
}
else
reply = ReplyMessage;
break;
case TitanicOperation.Close:
reply.Push (TitanicReturnCode.Ok.ToString ());
break;
default:
reply.Push (TitanicReturnCode.Failure.ToString ());
break;
}
Log ($"reply <{reply}>");
return reply;
}
示例11: PushMessage
public void PushMessage()
{
var message = new NetMQMessage();
Assert.AreEqual(0, message.FrameCount);
Assert.True(message.IsEmpty);
message.Append("Hello");
message.Push("Hello2");
Assert.AreEqual("Hello", message[1].ConvertToString());
Assert.AreEqual("Hello2", message[0].ConvertToString());
Assert.False(message.IsEmpty);
Assert.AreSame(message[0], message.First);
Assert.AreSame(message[1], message.Last);
Assert.AreNotSame(message[0], message[1]);
Assert.AreEqual(2, message.FrameCount);
}
示例12: SaveNewRequest_GuidAndRequest_ShouldUpdateQueue
public void SaveNewRequest_GuidAndRequest_ShouldUpdateQueue ()
{
var sut = new TitanicMemoryIO ();
var request = new NetMQMessage ();
request.Push ("A Request");
var id = Guid.NewGuid ();
var entry = new RequestEntry { RequestId = id, Request = request };
sut.SaveRequestEntry (entry);
var result = sut.GetRequestEntry (id);
sut.NumberOfRequests.Should ().Be (1, "because we just added one");
result.RequestId.Should ().Be (id);
result.Request.ShouldBeEquivalentTo (request);
result.Position.Should ().Be (-1);
result.State.Should ().Be (RequestEntry.Is_Pending);
}
示例13: Main
/// <summary>
/// usage: MDPServiceDiscoveryClientExample [-v]
///
/// implements a MDPClient API usage with Service Discovery
/// </summary>
private static void Main (string[] args)
{
const string service_to_lookup = "echo";
const string service_discovery = "mmi.service";
var verbose = args.Length == 1 && args[0] == "-v";
var id = Encoding.ASCII.GetBytes ("SDC01");
// give WORKER & BROKER time to settle
Thread.Sleep (250);
using (var session = new MDPClient ("tcp://localhost:5555", id))
{
if (verbose)
session.LogInfoReady += (s, e) => Console.WriteLine ("{0}", e.Info);
var request = new NetMQMessage ();
// set the service name
request.Push (service_to_lookup);
// send the request to service discovery
var reply = session.Send (service_discovery, request);
if (reply != null && !reply.IsEmpty)
{
var answer = reply.First.ConvertToString ();
Console.WriteLine ("Lookup {0} service returned: {1}/{2}", service_to_lookup, answer, reply);
}
else
Console.WriteLine ("ERROR: no response from broker, seems like broker is NOT running!");
}
Console.Write ("Exit with any key.");
Console.ReadKey ();
}
示例14: TitanicReply_RequestReplyPending_ShouldSentCorrectReply
public void TitanicReply_RequestReplyPending_ShouldSentCorrectReply ()
{
var io = new TitanicMemoryIO ();
using (var reqWorker = new FakeRequestMDPWorker ())
using (var repWorker = new FakeReplyMDPWorker ())
using (var closeWorker = new FakeCloseMDPWorker ())
using (var dispatchClient = new FakeDispatchMDPClient ())
using (var sut = new TitanicBroker (io))
{
// setup the queue with a request
var guid = Guid.NewGuid ();
var msg = new NetMQMessage ();
msg.Push (guid.ToString ());
// queue is setup with a request pending
io.SaveNewRequestEntry (guid, msg);
// setup the fake replyWorker's request
repWorker.Request = new NetMQMessage ();
repWorker.Request.Push (guid.ToString ());
// start the process chain - worker & client should only run until they hit an AutoResetEvent
Task.Factory.StartNew (() => sut.Run (reqWorker, repWorker, closeWorker, dispatchClient));
// signal worker to go ahead
repWorker.waitHandle.Set ();
// give everything some time to process
Thread.Sleep (_sleep_for);
// TEST COMMUNICATION
repWorker.Reply.FrameCount.Should ().Be (1, "because a 1 frame message is expected. ({0})", repWorker.Reply);
repWorker.Reply.First.ConvertToString ().Should ().Be ("Pending");
// TEST QUEUE
io.GetRequestEntries (e => e.RequestId == guid).Count ().Should ().Be (1);
var queueEntry = io.GetRequestEntry (guid);
queueEntry.State.Should ().Be (RequestEntry.Is_Pending);
io.ExistsMessage (TitanicOperation.Request, guid).Should ().BeTrue ();
io.ExistsMessage (TitanicOperation.Reply, guid).Should ().BeFalse ();
io.ExistsMessage (TitanicOperation.Close, guid).Should ().BeFalse ();
}
}
示例15: Wrap
/// <summary>
/// Prepend the message with an empty frame as separator and a frame
/// </summary>
/// <returns>new message with wrapped content</returns>
private NetMQMessage Wrap(NetMQMessage msg, NetMQFrame frame)
{
var result = new NetMQMessage(msg);
result.Push(NetMQFrame.Empty); // according to MDP an empty frame is the separator
result.Push(frame); // the return address
return result;
}