protected virtual void Dispose(bool disposing) { // release other disposable objects if (disposing) { //send destroy message to pipe self.Send(ActorKnownMessages.END_PIPE); } }
/// <summary> /// Release any contained resources. /// </summary> public void Dispose() { //send destroy message to pipe m_self.Options.SendTimeout = TimeSpan.Zero; try { m_self.Send(ActorKnownMessages.END_PIPE); m_self.WaitForSignal(); } catch (AgainException) {} m_shimTask.Wait(); m_self.Dispose(); }
public void RunPipeline(PairSocket shim) { while (true) { try { //Message for this actor/shim handler is expected to be //Frame[0] : Command //Frame[2] : AccountAction as JSON //Frame[1] : Account as JSON // //Result back to actor is a JSON message of the amended Account NetMQMessage msg = shim.ReceiveMessage(); string command = msg[0].ConvertToString(); if (command == ActorKnownMessages.END_PIPE) { break; } if (msg[0].ConvertToString() == "AMEND ACCOUNT") { string accountActionJson = msg[1].ConvertToString(); AccountAction accountAction = JsonConvert.DeserializeObject <AccountAction>(accountActionJson); string accountJson = msg[2].ConvertToString(); Account account = JsonConvert.DeserializeObject <Account>(accountJson); AmmendAccount(accountAction, account); shim.Send(JsonConvert.SerializeObject(account)); } else { shim.Send("Error: invalid message to actor"); } } //You WILL need to decide what Exceptions should be caught here, this is for //demonstration purposes only, any unhandled falut will bubble up to callers code catch (Exception e) { shim.Send(string.Format("Error: Exception occurred {0}", e.Message)); } } //broken out of work loop, so should dispose shim socket now shim.Dispose(); }
public void RunPipeline(PairSocket shim) { while (true) { try { NetMQMessage msg = shim.ReceiveMessage(); string command = msg[0].ConvertToString(); if (command == ActorKnownMessages.END_PIPE) { break; } //Simulate a failure that should be sent back to Actor //Simulate a failure that should be sent back to Actor //Simulate a failure that should be sent back to Actor //Simulate a failure that should be sent back to Actor throw new InvalidOperationException("Actors Shim threw an Exception"); } //You WILL need to decide what Exceptions should be caught here, this is for //demonstration purposes only, any unhandled falut will bubble up to callers code catch (InvalidOperationException e) { shim.Send(string.Format("Error: Exception occurred {0}", e.Message)); } } //broken out of work loop, so should dispose shim socket now shim.Dispose(); }
private void OnMessage(Message msg, PairSocket socket) { Console.WriteLine("> Recebido via OnMessage"); var op = msg.ReadNext <uint>(); if (op == ADD) { storedvalues.Add(msg.ReadNext <string>()); } else if (op == GET) { msg.Append(PRINT); foreach (var item in storedvalues) { msg.Append(item); } socket.Send(msg); } else { Console.WriteLine(msg.ToString()); //Show all package frames as String } }
public void Run(PairSocket shim) { shim.SignalOK(); while (true) { try { //Message for this actor/shim handler is expected to be //Frame[0] : Command //Frame[2] : AccountAction as JSON //Frame[1] : Account as JSON // //Result back to actor is a JSON message of the amended Account NetMQMessage msg = shim.ReceiveMultipartMessage(); string command = msg[0].ConvertToString(); if (command == NetMQActor.EndShimMessage) { break; } if (msg[0].ConvertToString() == "AMEND ACCOUNT") { string accountActionJson = msg[1].ConvertToString(); var accountAction = JsonConvert.DeserializeObject <AccountAction>(accountActionJson); string accountJson = msg[2].ConvertToString(); var account = JsonConvert.DeserializeObject <Account>(accountJson); AmmendAccount(accountAction, account); shim.Send(JsonConvert.SerializeObject(account)); } else { shim.Send("Error: invalid message to actor"); } } // You WILL need to decide what Exceptions should be caught here, this is for // demonstration purposes only, any unhandled fault will bubble up to caller's code. catch (Exception e) { shim.Send(string.Format("Error: Exception occurred {0}", e.Message)); } } }
public void Run(PairSocket shim) { shim.SignalOK(); while (true) { try { //Message for this actor/shim handler is expected to be //Frame[0] : Command //Frame[1] : Payload // //Result back to actor is a simple echoing of the Payload, where //the payload is prefixed with "ECHO BACK " NetMQMessage msg = shim.ReceiveMultipartMessage(); string command = msg[0].ConvertToString(); if (command == NetMQActor.EndShimMessage) { break; } if (command == "ECHO") { shim.Send(string.Format("ECHO BACK : {0}", msg[1].ConvertToString())); } else { shim.Send("Error: invalid message to actor"); } } // You WILL need to decide what Exceptions should be caught here, this is for // demonstration purposes only, any unhandled fault will bubble up to caller's code catch (Exception e) { shim.Send(string.Format("Error: Exception occurred {0}", e.Message)); } } }
private void OnMessage(Message msg, PairSocket socket) { Console.WriteLine("> Recebido via OnMessage"); var op = msg.ReadNext <uint>(); if (op == 1) { storedvalues.Add(msg.ReadNext <string>()); msg.Append(0); msg.Append("Adicionado"); socket.Send(msg); } else if (op == 2) { msg.Append(0); foreach (var item in storedvalues) { msg.Append(item + "\n"); } socket.Send(msg); } else if (op == 3) { var echoValue = msg.ReadNext <string>(); msg.Append(0); msg.Append(echoValue); socket.Send(msg); } else { Console.WriteLine(msg.ToString()); } }
private static void SendReceive(PairSocket s) { NanomsgSocketOptions.SetTimespan(s.SocketID, SocketOptionLevel.Default, SocketOption.RCVTIMEO, TimeSpan.FromMilliseconds(100)); while (true) { var data = s.Receive(); if (data != null) { Console.WriteLine("RECEIVED: '" + Encoding.UTF8.GetString(data) + "'"); } Thread.Sleep(TimeSpan.FromSeconds(1)); s.Send(Encoding.UTF8.GetBytes("the message is " + DateTime.Now.ToLongTimeString())); } }
public void Run(PairSocket shim, object[] args, CancellationToken token) { if (args == null || args.Count() != 1) { throw new InvalidOperationException( "Args were not correct, expected one argument"); } AccountAction accountAction = JsonConvert.DeserializeObject <AccountAction>(args[0].ToString()); while (!token.IsCancellationRequested) { //Message for this actor/shim handler is expected to be //Frame[0] : Command //Frame[1] : Payload // //Result back to actor is a simple echoing of the Payload, where //the payload is prefixed with "AMEND ACCOUNT" NetMQMessage msg = null; //this may throw NetMQException if we have disposed of the actor //end of the pipe, and the CancellationToken.IsCancellationRequested //did not get picked up this loop cycle msg = shim.ReceiveMessage(); if (msg == null) { break; } if (msg[0].ConvertToString() == "AMEND ACCOUNT") { string json = msg[1].ConvertToString(); Account account = JsonConvert.DeserializeObject <Account>(json); AmmendAccount(accountAction, account); shim.Send(JsonConvert.SerializeObject(account)); } else { throw NetMQException.Create("Unexpected command", ErrorCode.EFAULT); } } }
/// <summary> /// process a titanic request according to TITANIC Protocol /// /// <para>it connects via provided PAIR socket to main thread</para> /// <para>write request to disk and return the GUID to client</para> /// sends the GUID of the request back via the pipe for further processing /// </summary> internal void ProcessTitanicRequest([NotNull] PairSocket pipe, [CanBeNull] IMDPWorker mdpWorker = null) { // get a MDP worker with an automatic id and register with the service "titanic.request" // the worker will automatically start and connect to a MDP Broker at the indicated address using (var worker = mdpWorker ?? new MDPWorker(m_titanicAddress, TitanicOperation.Request.ToString())) { NetMQMessage reply = null; while (true) { // initiate the communication with sending a 'null', since there is no initial reply // a request should be [service name][request data] var request = worker.Receive(reply); Log(string.Format("[TITANIC REQUEST] Received request: {0}", request)); //! has there been a breaking cause? -> exit if (ReferenceEquals(request, null)) { break; } //! check if service exists! and return 'Unknown' if not // generate Guid for the request var requestId = Guid.NewGuid(); // save request to file -> [service name][request data] m_io.SaveMessage(TitanicOperation.Request, requestId, request); Log(string.Format("[TITANIC REQUEST] sending through pipe: {0}", requestId)); // send GUID through message queue to main thread pipe.Send(requestId.ToString()); // return GUID via reply message via worker.Receive call reply = new NetMQMessage(); // [Guid] reply.Push(requestId.ToString()); // [Ok][Guid] reply.Push(TitanicReturnCode.Ok.ToString()); Log(string.Format("[TITANIC REQUEST] sending reply: {0}", reply)); } } }
private void Start() { pairSocket = new PairSocket(); pairSocket.OnClientDisconnect += OnDisconnected; pairSocket.OnMessage += OnMessage; while (true) { var success = pairSocket.TryConnect("tcp://127.0.0.1:5001", 500); if (success) { Console.Title = "Client: " + pairSocket.ConnectionId; // Tokens podem ser adicioandos assim também var msg = new Message(1, "Hello Server :)"); pairSocket.Send(msg); pairSocket.Subscribe("connecteds", PubSubQueueLostType.LastMessage); pairSocket.Publish("connecteds", new Message(0, "Chegando ae na area " + pairSocket.ConnectionId)); pairSocket.SetLastWill("offline", new Message(0, "Meti o pé " + pairSocket.ConnectionId)); // Sleep apenas para que o Console não fique com mensagens misturadas e atrapalhe o entendimento do exemplo // Em um cenário real, não precisaria de qualquer tipo de delay Thread.Sleep(500); //pairSocket.Close(); //var _success = false; //while(!_success) //{ // Thread.Sleep(10000); // success = pairSocket.TryReconnect(); //} DoCommunication(); } else { Console.WriteLine("> Conexão não foi estabelecida, pressione qualquer tecla para tentar novamente"); Console.ReadKey(); } } }
public void Run(PairSocket shim, object[] args, CancellationToken token) { if (args == null || args.Count() != 1 || (string)args[0] != "Hello World") { throw new InvalidOperationException( "Args were not correct, expected 'Hello World'"); } while (!token.IsCancellationRequested) { //Message for this actor/shim handler is expected to be //Frame[0] : Command //Frame[1] : Payload // //Result back to actor is a simple echoing of the Payload, where //the payload is prefixed with "ECHO BACK " NetMQMessage msg = null; //this may throw NetMQException if we have disposed of the actor //end of the pipe, and the CancellationToken.IsCancellationRequested //did not get picked up this loop cycle msg = shim.ReceiveMessage(); if (msg == null) { break; } if (msg[0].ConvertToString() == "ECHO") { shim.Send(string.Format("ECHO BACK : {0}", msg[1].ConvertToString())); } else { throw NetMQException.Create("Unexpected command", ErrorCode.EFAULT); } } }
public void Run(PairSocket shim, object[] args, CancellationToken token) { if (args == null || args.Count() != 1) throw new InvalidOperationException( "Args were not correct, expected one argument"); AccountAction accountAction = JsonConvert.DeserializeObject<AccountAction>(args[0].ToString()); while (!token.IsCancellationRequested) { //Message for this actor/shim handler is expected to be //Frame[0] : Command //Frame[1] : Payload // //Result back to actor is a simple echoing of the Payload, where //the payload is prefixed with "AMEND ACCOUNT" NetMQMessage msg = null; //this may throw NetMQException if we have disposed of the actor //end of the pipe, and the CancellationToken.IsCancellationRequested //did not get picked up this loop cycle msg = shim.ReceiveMessage(); if (msg == null) break; if (msg[0].ConvertToString() == "AMEND ACCOUNT") { string json = msg[1].ConvertToString(); Account account = JsonConvert.DeserializeObject<Account>(json); AmmendAccount(accountAction, account); shim.Send(JsonConvert.SerializeObject(account)); } else { throw NetMQException.Create("Unexpected command", ErrorCode.EFAULT); } } }
public void Run(PairSocket shim, object[] args, CancellationToken token) { if (args == null || args.Count() != 1 || (string)args[0] != "Hello World") throw new InvalidOperationException( "Args were not correct, expected 'Hello World'"); while (!token.IsCancellationRequested) { //Message for this actor/shim handler is expected to be //Frame[0] : Command //Frame[1] : Payload // //Result back to actor is a simple echoing of the Payload, where //the payload is prefixed with "ECHO BACK " NetMQMessage msg = null; //this may throw NetMQException if we have disposed of the actor //end of the pipe, and the CancellationToken.IsCancellationRequested //did not get picked up this loop cycle msg = shim.ReceiveMessage(); if (msg == null) break; if (msg[0].ConvertToString() == "ECHO") { shim.Send(string.Format("ECHO BACK : {0}", msg[1].ConvertToString())); } else { throw NetMQException.Create("Unexpected command", ErrorCode.EFAULT); } } }
public void Send(ref Msg msg, SendReceiveOptions options) { m_self.Send(ref msg, options); }
public void Send(ref Msg msg) { m_messagesPipe.Send(ref msg, true); }
public void Send(byte[] data, int length, bool dontWait = false, bool sendMore = false) { self.Send(data, length, dontWait, sendMore); }
public void Send(ref Msg msg, SendReceiveOptions options) { m_messagesPipe.Send(ref msg, options); }