public NetMQMessage DecryptApplicationMessage(NetMQMessage cipherMessage) { if (!SecureChannelReady) { throw new NetMQSecurityException(NetMQSecurityErrorCode.SecureChannelNotReady, "Cannot decrypt messages until the secure channel is ready"); } if (cipherMessage == null) { throw new ArgumentNullException("cipherMessage is null"); } if (cipherMessage.FrameCount < 2) { throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "cipher message should have at least 2 frames"); } NetMQFrame protocolVersionFrame = cipherMessage.Pop(); NetMQFrame contentTypeFrame = cipherMessage.Pop(); if (!protocolVersionFrame.ToByteArray().SequenceEqual(m_protocolVersion)) { throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidProtocolVersion, "Wrong protocol version"); } ContentType contentType = (ContentType)contentTypeFrame.Buffer[0]; if (contentType != ContentType.ApplicationData) { throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidContentType, "Not an applicagtion data message"); } return m_recordLayer.DecryptMessage(ContentType.ApplicationData, cipherMessage); }
private CommitForStorage getCommit(NetMQMessage message) { var context = message.Pop().ConvertToString(); var stream = message.Pop().ConvertToString(); var expectedVersion = message.PopInt64(); var eventCount = message.PopInt32(); var events = new EventForStorage[eventCount]; for (int i = 0; i < eventCount; i++) { var eventId = new Guid(message.Pop().ToByteArray()); var timestamp = message.PopDateTime(); var typeKey = message.PopString(); var headers = message.PopStringOrNull(); var body = message.PopString(); //-1 to override concurrency check. Being lazy and not using a constant. var version = expectedVersion == -1 ? -1 : expectedVersion + i; events[i] = new EventForStorage(eventId, version, timestamp, typeKey, headers, body); } return new CommitForStorage(context, stream, events); }
public static NetMQMessage CreateMessage(string topic, byte[] data) { var message = new NetMQMessage(); if (!string.IsNullOrEmpty(topic)) message.Append(Encoding.Unicode.GetBytes(topic)); message.Append(data); return message; }
/// <summary> /// Try to send request message and return the response as a message, or return null if not successful /// </summary> /// <param name="address">a string denoting the address to connect to</param> /// <param name="requestMessage">The request message</param> /// <param name="numTries">The number of times to try</param> /// <param name="requestTimeout">The timeout for each request</param> /// <param name="progressPublisher">Report topics: Failure, Retry, Send, Success</param> /// <returns>the response message, or null if not successful</returns> public static NetMQMessage RequestResponseMultipartMessageWithRetry([NotNull] string address, [NotNull] NetMQMessage requestMessage, int numTries, TimeSpan requestTimeout, PublisherSocket progressPublisher = null) { var responseMessage = new NetMQMessage(); while (numTries-- > 0) { using (var requestSocket = new RequestSocket(address)) { progressPublisher?.SendFrame(ProgressTopic.Send.ToString()); requestSocket.SendMultipartMessage(requestMessage); if (requestSocket.TryReceiveMultipartMessage(requestTimeout, ref responseMessage)) { progressPublisher?.SendFrame(ProgressTopic.Success.ToString()); return responseMessage; } progressPublisher?.SendFrame(ProgressTopic.Retry.ToString()); } } progressPublisher?.SendFrame(ProgressTopic.Failure.ToString()); return null; }
public virtual NetMQMessage ToNetMQMessage() { NetMQMessage message = new NetMQMessage(); message.Append(new byte[] { (byte)HandshakeType }); return message; }
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; }
public void DesktopClient_WillAccept_SinglePartMessages() { Queue<Packet> packets = new Queue<Packet>(); // Mock the the message handler processor var messageHandler = new Mock<IDesktopMessageHandler>(); messageHandler.Setup(mh => mh.DisplayLogPacket(It.IsAny<LogPacket>())).Callback( (LogPacket packet) => { packets.Enqueue(packet); }).Verifiable(); // Setup Client StartClientThread(messageHandler.Object); using (PushSocket server = new PushSocket("@tcp://*:" + _port)) { var message = new NetMQMessage(); message.Append(JsonConvert.SerializeObject(new LogPacket())); server.SendMultipartMessage(message); } // Give NetMQ time to send the message Thread.Sleep(500); Assert.IsTrue(packets.Count == 1); }
public void RequestResponseMultipartMessageWithRetryFails() { const string address = "tcp://127.0.0.1:50002"; const string pubAddress = "tcp://127.0.0.1:60002"; const int numTries = 5; var requestTimeout = TimeSpan.FromMilliseconds(100); var requestMessage = new NetMQMessage(1); requestMessage.Append("Hi"); using (var progressPublisher = new PublisherSocket(pubAddress)) using (var progressSubscriber = new SubscriberSocket(pubAddress)) using (var server = new RouterSocket(address)) { progressSubscriber.SubscribeToAnyTopic(); var progressProactor = new NetMQProactor(progressSubscriber, (socket, message) => Console.WriteLine("C: {0} {1:ss.fff}", message[0].ConvertToString(), DateTime.Now)); var serverProactor = new NetMQProactor(server, (socket, message) => { Console.WriteLine("ResponseEcho recieved message {0} at {1:ss.fff}", message[2].ConvertToString(), DateTime.Now); }); using (serverProactor) using (progressProactor) { var responseMessage = RequestSocket.RequestResponseMultipartMessageWithRetry(address, requestMessage, numTries, requestTimeout, progressPublisher); Assert.IsNull(responseMessage); } } }
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); }
/// <summary> /// Remove the three frames from the given NetMQMessage, interpreting them thusly: /// 1. a byte with the HandshakeType, presumed here to be ClientHello, /// 2. a byte-array containing the RandomNumber, /// 3. a byte-array with the list of CipherSuites. /// </summary> /// <param name="message">a NetMQMessage - which must have 2 frames</param> /// <exception cref="NetMQSecurityException"><see cref="NetMQSecurityErrorCode.InvalidFramesCount"/>: FrameCount must be 3.</exception> public override void SetFromNetMQMessage(NetMQMessage message) { base.SetFromNetMQMessage(message); if (message.FrameCount != 3) { throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message"); } // get the random number NetMQFrame randomNumberFrame = message.Pop(); RandomNumber = randomNumberFrame.ToByteArray(); // get the length of the cipher-suites array NetMQFrame ciphersLengthFrame = message.Pop(); int ciphersLength = BitConverter.ToInt32(ciphersLengthFrame.Buffer, 0); // get the cipher-suites NetMQFrame ciphersFrame = message.Pop(); CipherSuites = new CipherSuite[ciphersLength]; for (int i = 0; i < ciphersLength; i++) { CipherSuites[i] = (CipherSuite)ciphersFrame.Buffer[i * 2 + 1]; } }
protected static void EncodeVector01(Vector3 val, NetMQMessage msg) { // TODO: Maybe optimize this to pack into a single integer? Probably not really necessary EncodeFloat01(val.x, msg); EncodeFloat01(val.y, msg); EncodeFloat01(val.z, msg); }
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 :-) }
internal WebSocketClient(NetMQSocket streamSocket, byte[] identity) { m_state = WebSocketClientState.Closed; m_streamSocket = streamSocket; m_outgoingMessage = null; Identity = identity; }
protected static Vector3 ReadVector01(NetMQMessage msg, ref int curIndex) { Vector3 ret = Vector3.zero; ret.x = ReadFloat01(msg, ref curIndex); ret.y = ReadFloat01(msg, ref curIndex); ret.z = ReadFloat01(msg, ref curIndex); return ret; }
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")); } }
public override void SetFromNetMQMessage(NetMQMessage message) { base.SetFromNetMQMessage(message); if (message.FrameCount != 0) { throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message"); } }
/// <summary> /// Send a message to the _server using ZeroMQ /// </summary> /// <param name="packet">Packet to transmit</param> public void Transmit(Packet packet) { var payload = JsonConvert.SerializeObject(packet); var message = new NetMQMessage(); message.Append(payload); _server.SendMultipartMessage(message); }
public void AppendInt32() { NetMQMessage message = new NetMQMessage(); message.Append("Hello"); message.Append(5); Assert.AreEqual(4, message[1].MessageSize); Assert.AreEqual(5, message[1].ConvertToInt32()); }
public void Handle(NetMQFrame[] sender, NetMQMessage message) { Log.Debug("[CommitHandler] Got a commit to write..."); var requestId = message.Pop(); var commit = getCommit(message); var task = _writer.Store(commit); var commitContinuationContext = new CommitContinuationContext(sender, commit.CommitId, requestId); task.ContinueWith(onComplete, commitContinuationContext, TaskContinuationOptions.ExecuteSynchronously); Log.Debug("[CommitHandler] Commit queued up..."); }
public virtual void SetFromNetMQMessage(NetMQMessage message) { if (message.FrameCount == 0) { throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message"); } // remove the handshake type column message.Pop(); }
public async Task SendMessage(NetMQMessage message) { // instead of creating inproc socket which listen to messages and then send //to the server we just creating task and run a code on // the poller thread which the the thread of the clientSocket Task task = new Task(() => clientSocket.SendMessage(message)); task.Start(scheduler); await task; await ReceiveMessage(); }
public void CallMethod_Using_NProxyWrapper_ReadMessageWithRawActor() { waitHandle.Reset(); using (var context = NetMQContext.Create()) { using (var exchange = new Exchange(context)) { exchange.Start(); var queueDevice = new QueueDevice( context, Pipe.PubSubControlBackAddressServer, Pipe.PubSubControlFrontAddressServer, DeviceMode.Threaded); queueDevice.Start(); Thread.Sleep(200); var task = Task.Run(() => { return RunSubscriber(context); }); using (var actor = new Actor(context, new BinarySerializer())) { using (var syncService = context.CreateResponseSocket()) { syncService.Connect(Pipe.PubSubControlFrontAddressClient); for (int i = 0; i < 1; i++) { syncService.Receive(); syncService.Send(string.Empty); } var order = actor.CreateInstance<IOrder>(typeof(Order)); Assert.IsInstanceOfType(order, typeof(IOrder)); order.UpdateDescription("XXX"); //called without exception waitHandle.WaitOne(); var netMqMessage = new NetMQMessage(); netMqMessage.Append(new NetMQFrame(string.Empty)); netMqMessage.Append(new NetMQFrame("shutdownallactors")); actor.OutputChannel.SendMessage(netMqMessage); //actor.SendKillSignal(actor.Serializer, actor.OutputChannel, string.Empty); } } Thread.Sleep(200); queueDevice.Stop(true); exchange.Stop(true); } } }
public void AppendInt64() { long num = (long)int.MaxValue + 1; NetMQMessage message = new NetMQMessage(); message.Append("Hello"); message.Append(num); Assert.AreEqual(8, message[1].MessageSize); Assert.AreEqual(num, message[1].ConvertToInt64()); }
public void Handle(NetMQFrame[] sender, NetMQMessage message) { Logger.Debug("[Queue_SubscribeHandler] Received subscribe request."); var requestId = message.Pop(); var context = message.Pop().ConvertToString(); var queueId = message.Pop().ConvertToString(); var subscriberId = message.Pop().ConvertToString(); var filter = message.Pop().ConvertToString(); var utcStartTime = message.PopDateTime(); var allocationSize = message.PopInt32(); var allocationTimeInMilliseconds = message.PopInt32(); var subscribe = new SubscribeToQueue(context, queueId, subscriberId, filter, utcStartTime, allocationSize, allocationTimeInMilliseconds); var queuedEvents = _storage.Subscribe(subscribe); var events = queuedEvents.Events; var msg = new NetMQMessage(); msg.Append(sender); msg.AppendEmptyFrame(); msg.Append(ResProtocol.ResClient01); msg.Append(requestId); msg.Append(ResCommands.QueuedEvents); msg.Append(context); msg.Append(queueId); msg.Append(subscriberId); msg.Append(DateTime.UtcNow.ToNetMqFrame()); msg.Append(queuedEvents.AllocationId.ToNetMqFrame()); var count = events.Length; msg.Append(count.ToNetMqFrame()); foreach (var e in events) { msg.Append(e.EventId.ToByteArray()); msg.Append(e.Stream); msg.Append(e.Context); msg.Append(e.Sequence.ToNetMqFrame()); msg.Append(e.Timestamp.ToNetMqFrame()); msg.Append(e.TypeKey); msg.Append(e.Headers.ToNetMqFrame()); msg.Append(e.Body); } var result = new QueuedMessagesFetched(msg); while (!_outBuffer.Offer(result)) _spin.SpinOnce(); }
public static void ReceiveMessage(this IReceivingSocket socket, NetMQMessage message, bool dontWait = false) { message.Clear(); bool more = true; while (more) { byte[] buffer = socket.Receive(dontWait, out more); message.Append(buffer); } }
public void ClientToServerMessage() { NetMQMessage plainMessage = new NetMQMessage(); plainMessage.Append("Hello"); NetMQMessage cipherMessage = m_clientSecureChannel.EncryptApplicationMessage(plainMessage); NetMQMessage decryptedMessage = m_serverSecureChannel.DecryptApplicationMessage(cipherMessage); Assert.AreEqual(decryptedMessage[0].ConvertToString(), plainMessage[0].ConvertToString()); Assert.AreEqual(decryptedMessage[0].ConvertToString(), "Hello"); }
public Action<NetMQMessage> Send(NetMQSocket socket, PendingResRequest pendingRequest, Guid requestId) { var pending = (PendingResRequest<QueryEventsForStreamResponse>) pendingRequest; var msg = new NetMQMessage(); msg.AppendEmptyFrame(); msg.Append(ResProtocol.ResClient01); msg.Append(ResCommands.QueryEventsByStream); msg.Append(requestId.ToByteArray()); msg.Append(_context); msg.Append(_stream); msg.Append(_fromVersion.ToNetMqFrame()); msg.Append(_maxVersion.ToNetMqFrame()); socket.SendMultipartMessage(msg); return m => { var command = m.Pop().ConvertToString(); if (command == ResCommands.Error) { var errorCode = m.Pop().ConvertToString(); var errorDetails = m.Pop().ConvertToString(); ErrorResolver.RaiseException(errorCode, errorDetails, pending.SetException); return; } if (command != ResCommands.QueryEventsByStreamResponse) pending.SetException(new UnsupportedCommandException(command)); var count = m.PopInt32(); var events = new EventInStorage[count]; for (var i = 0; i < count; i++) { var id = new Guid(m.Pop().ToByteArray()); var streamId = m.Pop().ConvertToString(); var context = m.Pop().ConvertToString(); var sequence = m.PopInt64(); var timestamp = m.PopDateTime();; var type = m.PopString(); var headers = m.PopStringOrNull(); var body = m.PopString(); events[i] = new EventInStorage(context, streamId, sequence, type, id, headers, body, timestamp); } var result = new QueryEventsForStreamResponse(_context, _stream, events); pending.SetResult(result); }; }
public void ProcessMessage(NetMQMessage message, NetMQSocket socket) { if (message.FrameCount < 3) throw new MalformedMessageReceivedException(message.FrameCount); var sender = message.PopUntilEmptyFrame(); var protocolFrame = message.Pop(); var protocol = protocolFrame.ConvertToString(); ensureProtocol(protocol); var command = message.Pop().ConvertToString(); _dispatcher.Dispatch(command, sender, message); }
/// <summary> /// Remove the two frames from the given NetMQMessage, interpreting them thusly: /// 1. a byte with the HandshakeType, assumed to be ClientKeyExchange /// 2. a byte-array containing the EncryptedPreMasterSecret. /// </summary> /// <param name="message">a NetMQMessage - which must have 2 frames</param> public override void SetFromNetMQMessage(NetMQMessage message) { base.SetFromNetMQMessage(message); if (message.FrameCount != 1) { throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message"); } NetMQFrame preMasterSecretFrame = message.Pop(); EncryptedPreMasterSecret = preMasterSecretFrame.ToByteArray(); }
public override void SetFromNetMQMessage(NetMQMessage message) { base.SetFromNetMQMessage(message); if (message.FrameCount != 1) { throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message"); } NetMQFrame verifyDataFrame = message.Pop(); VerifyData = verifyDataFrame.ToByteArray(); }
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); }
public void SaveProcessedRequest_ExistingRequestWithRequestData_ShouldUpdateEntryAppropriate() { var sut = new TitanicMemoryIO(); var request = new NetMQMessage(); request.Push("Processed Request Data"); var id = Guid.NewGuid(); var entry = new RequestEntry { RequestId = id, Request = request }; sut.SaveRequestEntry(entry); sut.SaveProcessedRequestEntry(entry); var result = sut.GetRequestEntry(id); result.RequestId.Should().Be(id); result.Request.ShouldBeEquivalentTo(request); result.Position.Should().Be(-1); result.State.Should().Be(RequestEntry.Is_Processed); }
private void OnMessageReceived(object sender, NetMQSocketEventArgs e) { NetMQMessage message = null; if (!socket.TryReceiveMultipartMessage(ref message, 2)) { return; } // Move handling request off NetMQPoller thread and onto TaskPool as soon as possible Task.Run(() => { if (!messageFactory.IsValidTopicMessage(message)) { return; } var package = messageFactory.ExtractTopic(message); topicDispatcher.Handle(this, package); }); }
private IList <Erg> ReceiveBoats() { //try to receive something from the network... return all the ergs we get var message = new NetMQMessage(); IList <EasyErgsocket.Erg> receivedBoats = new List <EasyErgsocket.Erg>(); while (subSocket.TryReceiveMultipartMessage(System.TimeSpan.Zero, ref message)) { foreach (var frame in message.Skip(1)) //the first frame is always just the envelope/topic... let's ignore it by using Linq { byte[] rawMessage = frame.Buffer; using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(rawMessage)) { var givenErg = Serializer.Deserialize <EasyErgsocket.Erg>(memoryStream); receivedBoats.Add(givenErg); } } } return(receivedBoats); }
/// <summary> /// Remove the three frames from the given NetMQMessage, interpreting them thusly: /// 1. a byte with the <see cref="HandshakeType"/>, /// 2. RandomNumber (a byte-array), /// 3. a 2-byte array with the <see cref="CipherSuite"/> in the 2nd byte. /// </summary> /// <param name="message">a NetMQMessage - which must have 3 frames</param> /// <exception cref="NetMQSecurityException"><see cref="NetMQSecurityErrorCode.InvalidFramesCount"/>: FrameCount must be 2.</exception> public override void SetFromNetMQMessage(NetMQMessage message) { if (message.FrameCount != 4) { throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message"); } // Get the random number NetMQFrame randomNumberFrame = message.Pop(); RandomNumber = randomNumberFrame.ToByteArray(); NetMQFrame sessionIDLengthFrame = message.Pop(); NetMQFrame sessionIDFrame = message.Pop(); //设置sessionid this.SessionID = sessionIDFrame.ToByteArray(); // Get the cipher suite NetMQFrame cipherSuiteFrame = message.Pop(); CipherSuite = (CipherSuite)cipherSuiteFrame.Buffer[1]; }
private static void Main() { using (var context = NetMQContext.Create()) using (var client = context.CreateRequestSocket()) { client.Connect(ClientEndpoint); for (var i = 0; i < 10; i++) { var msg = new NetMQMessage(); msg.Append("Message_" + i); client.SendMessage(msg); Console.WriteLine("Sent Message {0}", msg.Last.ConvertToString()); var response = client.ReceiveMultipartMessage(); Console.WriteLine("Received Message {0}", response.Last.ConvertToString()); } Console.ReadKey(); } }
/// <summary> /// Send parameters of the reccam which aren't bytes. Convert the value to send to 4 bytes /// </summary> /// <param name="module"></param> /// <param name="action"></param> /// <param name="config"></param> /// <param name="valueByte1"></param> /// <param name="valueByte2"></param> /// <param name="valueByte3"></param> /// <param name="valueByte4"></param> /// <returns></returns> public bool sendCommand(byte module, byte action, byte config, byte valueByte1, byte valueByte2, byte valueByte3, byte valueByte4) { byte[] header_bytes = new byte[8] { (byte)'A', module, action, config, valueByte1, valueByte2, valueByte3, valueByte4 }; NetMQMessage req_msg = new NetMQMessage(); req_msg.Append(header_bytes); NetMQ.Msg resp_msg = new StdMessage(0x00, 0x00).to_Msg(); // it will be filled when receiving the response ## la respuesta de dos partes sigue siendo de este tipo? reqSrv = new ReliableExternalClient( GlobalSettings.Instance.getRequestPort(), TimeSpan.FromMilliseconds(1000), 3); if (!reqSrv.sendAndReceive(ref req_msg, ref resp_msg)) { UnityEngine.Debug.Log("Client: server not respoding"); return(false); } return(true); }
public void ParseData(object s, NetMQSocketEventArgs eventArgs) { NetMQMessage m = new NetMQMessage(); while (eventArgs.Socket.TryReceiveMultipartMessage(ref m)) { string msgType = m[0].ConvertToString(); MemoryStream mStream = new MemoryStream(m[1].ToByteArray()); byte[] thirdFrame = null; if (m.FrameCount >= 3) { thirdFrame = m[2].ToByteArray(); } if (OnReceiveData != null) { OnReceiveData(msgType, MessagePackSerializer.Deserialize <Dictionary <string, object> >(mStream), thirdFrame); } } }
/// <summary> /// Command to load a plan on the Plan executor /// </summary> /// <param name="loadPlan"></param> /// <param name="guid"></param> /// <returns></returns> public bool sendTwoPartCommand(LoadPlan loadPlan, string guid) { byte[] header_bytes = new byte[4] { (byte)'A', loadPlan.PlanHeader.module, loadPlan.PlanHeader.action, loadPlan.indexPath }; NetMQMessage req_msg = new NetMQMessage(); req_msg.Append(header_bytes); req_msg.Append(guid); NetMQ.Msg resp_msg = new StdMessage(0x00, 0x00).to_Msg(); // it will be filled when receiving the response ## la respuesta de dos partes sigue siendo de este tipo? reqSrv = new ReliableExternalClient( GlobalSettings.Instance.getRequestPort(), TimeSpan.FromMilliseconds(1000), 3); if (!reqSrv.sendAndReceive(ref req_msg, ref resp_msg)) { UnityEngine.Debug.Log("Client: server not respoding"); return(false); } return(true); }
private void Run() { while (_running) { //check for time/cutoffs to trigger events... try { NetMQMessage msg = _socket.ReceiveMessage(); if (msg.IsEmpty) { continue; } ProcessRequest(msg[0].Buffer); } catch (Exception e) { _running = false; } } _socket.Dispose(); }
private void OnClientKeyExchange(NetMQMessage incomingMessage, OutgoingMessageBag outgoingMessages) { if (m_lastReceivedMessage != HandshakeType.ClientHello || m_lastSentMessage != HandshakeType.ServerHelloDone) { throw new NetMQSecurityException(NetMQSecurityErrorCode.HandshakeUnexpectedMessage, "Client Key Exchange received when expecting another message"); } HashLocalAndRemote(incomingMessage); ClientKeyExchangeMessage clientKeyExchangeMessage = new ClientKeyExchangeMessage(); clientKeyExchangeMessage.SetFromNetMQMessage(incomingMessage); RSACryptoServiceProvider rsa = LocalCertificate.PrivateKey as RSACryptoServiceProvider; byte[] premasterSecret = rsa.Decrypt(clientKeyExchangeMessage.EncryptedPreMasterSecret, false); GenerateMasterSecret(premasterSecret); InvokeChangeCipherSuite(); }
private void OnClientHello(NetMQMessage incomingMessage, OutgoingMessageBag outgoingMessages) { if (m_lastReceivedMessage != HandshakeType.HelloRequest || m_lastSentMessage != HandshakeType.HelloRequest) { throw new NetMQSecurityException(NetMQSecurityErrorCode.HandshakeUnexpectedMessage, "Client Hello received when expecting another message"); } HashLocalAndRemote(incomingMessage); ClientHelloMessage clientHelloMessage = new ClientHelloMessage(); clientHelloMessage.SetFromNetMQMessage(incomingMessage); SecurityParameters.ClientRandom = clientHelloMessage.RandomNumber; AddServerHelloMessage(outgoingMessages, clientHelloMessage.CipherSuites); AddCertificateMessage(outgoingMessages); AddServerHelloDone(outgoingMessages); }
public void Decode() { BlockHash[] blockHashes = GenerateRandomBlockHashes(100L).ToArray(); var msg = new BlockHashes(123, blockHashes); Assert.Equal(123, msg.StartIndex); Assert.Equal(blockHashes, msg.Hashes); var privKey = new PrivateKey(); AppProtocolVersion apv = AppProtocolVersion.Sign(privKey, 3); Peer peer = new BoundPeer(privKey.PublicKey, new DnsEndPoint("0.0.0.0", 1234)); var messageCodec = new NetMQMessageCodec(appProtocolVersion: apv); NetMQMessage encoded = messageCodec.Encode( msg, privKey, peer, DateTimeOffset.UtcNow); BlockHashes restored = (BlockHashes)messageCodec.Decode(encoded, true); Assert.Equal(msg.StartIndex, restored.StartIndex); Assert.Equal(msg.Hashes, restored.Hashes); }
private byte[] Send(byte[] request) { try { //SendStatus result = _socket.Send(request); //if (result != SendStatus.Sent) // throw new Exception("Error sending message on socket"); NetMQMessage msg = _socket.ReceiveMessage(); //TODO:TimeSpan.FromSeconds(5) if (msg.IsEmpty) { return(new byte[0]); } return(msg[0].Buffer); } catch (Exception e) { Console.WriteLine(e); return(new byte[0]); } }
/// <summary> /// Return a new NetMQMessage that holds two frames: /// 1. a frame with a single byte representing the HandshakeType, which is Certificate, /// 2. a frame containing the certificate that has been exported to a byte-array. /// </summary> /// <returns>the resulting new NetMQMessage</returns> public override NetMQMessage ToNetMQMessage() { NetMQMessage message = AddHandShakeType(); byte[] certBytes = Certificate.Export(X509ContentType.Cert); //加长度,证书总长度 var certsLengthBytes = BitConverter.GetBytes(certBytes.Length + 3); message.Append(new byte[] { certsLengthBytes[2], certsLengthBytes[1], certsLengthBytes[0] }); //每个证书的长度和证书 var certLengthBytes = BitConverter.GetBytes(certBytes.Length); message.Append(new byte[] { certLengthBytes[2], certLengthBytes[1], certLengthBytes[0] }); message.Append(certBytes); var handShakeType = message.Pop(); InsertLength(message); message.Push(handShakeType); return(message); }
static void Main(string[] args) { using (var ctx = NetMQContext.Create()) { using (var client = ctx.CreateRequestSocket()) { client.Connect(CLIENT_ENDPOINT); for (var i = 0; i < 10; i++) { var msg = new NetMQMessage(); msg.Append("Message_" + i); client.SendMessage(msg); Console.WriteLine("Sent Message {0}", msg.Last.ConvertToString()); var response = client.ReceiveMessage(); Console.WriteLine("Received Message {0}", response.Last.ConvertToString()); } Console.ReadKey(); } } }
/// <summary> /// 收到客户端请求,交由Actor进行处理 /// </summary> /// <param name="protocolPackage"></param> /// <param name="body"></param> public virtual void ProcessRequest(ProtocolPackage protocolPackage, byte[] body) { if (protocolPackage == null) { return; } var request = protocolPackage.UnPackToPacket(body); var msg = new NetMQMessage(); msg.Append(new byte[] { 1 }); //版本号 msg.Append("req"); //动作 msg.Append(protocolPackage.SessionID); //sessionid msg.Append(protocolPackage.PackKeys); //客户端密钥 msg.Append(protocolPackage.UnPackKeys); //服务端密钥 msg.Append(request.HeaderBytes); //信息头 msg.Append(request.ContentBytes); //信息体 //加入队列 PushQueue.Enqueue(msg); }
public void Run() { while (true) { var request = server.ReceiveMultipartMessage(); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Received a message from client at " + DateTime.Now); Console.ForegroundColor = ConsoleColor.White; var response = new NetMQMessage(); var clientAddress = request[0]; response.Append(clientAddress); var phrase = recognizer.Recognize(request[1].ToByteArray()); var result = parser.ParsePhrase(phrase); server.SendMultipartMessage(CreateResponse(response, result)); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Sent a message with header: " + response[1].ConvertToString(Encoding.UTF8) + " at " + DateTime.Now); Console.ForegroundColor = ConsoleColor.White; } }
public void Run() { var t = new Task(() => { var g = new MDPWorker("tcp://localhost:5555", parent.GetServiceName(bucketId), Encoding.ASCII.GetBytes(parent.GetServiceName(bucketId))); // logging info to be displayed on screen g.LogInfoReady += (s, e) => Console.WriteLine($"{e.Info}"); // there is no initial reply NetMQMessage reply = null; bool exit = false; while (!exit) { // send the reply and wait for a request var request = g.Receive(reply); Console.WriteLine($"Received a request"); // was the worker interrupted if (ReferenceEquals(request, null)) { break; } // echo the request if (OnReceived != null) { reply = OnReceived(request); } else { throw new Exception("OnReceived handler is null - is handler set?"); } } }); t.Start(); }
//Provide People to the client public static void ProvidePeople() { using (var server = new ResponseSocket(Config.URL)) using (var poller = new NetMQPoller { server }) { var reader = new Reader(); server.ReceiveReady += (sender, e) => { var command = e.Socket.ReceiveFrameString(); switch (command.ToLower()) { case "getpeople": List <IPerson> people = reader.ReadData(Config.DATA_FILE_PATH); var message = new NetMQMessage(people.Count - 1); people.ForEach(p => message.Append(p.ToString())); e.Socket.SendMultipartMessage(message); break; default: e.Socket.SendFrame(String.Format(Config.DEFAULT_SERVICE_MESSAGE, command)); break; } Console.Read(); }; poller.Run(); Console.Read(); } }
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)); } } }
public void CreateBucket(NetMQMessage message) { Message <BucketMessage> msg = new Message <BucketMessage>(message); string absolutePath = MessageHelper.GetAbsolutePath(_path, msg, _tokenManager); string bucketName = null; if (absolutePath == null) { msg.Data.Successful = false; } else { if (!Directory.Exists(HomePath(msg.Data.Token))) { FileSystemService.CreateFolder(HomePath(msg.Data.Token)); } if (FileSystemService.NumberOfDirectories(HomePath(msg.Data.Token)) < 5) { bucketName = FileSystemService.CreateFolder(absolutePath); msg.Data.Successful = bucketName != null; } else { SendErrorMessage("Maximum number of buckets is 5", Either.Enums.ErrorCode.NumberOfBucketsExeeded, msg.Id); return; } } if (msg.Data.Successful) { msg.Topic = _returnTopic; msg.Data.ReturnItems.Add(bucketName); SendMessage(msg.ToNetMQMessage()); } else { SendErrorMessage("Create bucket error", Either.Enums.ErrorCode.CreateBucketError, msg.Id); } }
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 RouterDealerMessaging() { using (NetMQContext context = NetMQContext.Create()) { using (var server = context.CreateRouterSocket()) { server.Bind("tcp://127.0.0.1:5555"); using (var client = context.CreateDealerSocket()) { client.Connect("tcp://127.0.0.1:5555"); NetMQMessage clientOutgoingMessage = new NetMQMessage(); clientOutgoingMessage.Append("Hello"); client.SendMessage(clientOutgoingMessage); NetMQMessage serverIncomingMessage = server.ReceiveMessage(); // number of frames should be one because first message should be identity of client Assert.AreEqual(2, serverIncomingMessage.FrameCount); Assert.AreEqual("Hello", serverIncomingMessage[1].ConvertToString()); NetMQMessage serverOutgoingMessage = new NetMQMessage(); // first adding the identity serverOutgoingMessage.Append(serverIncomingMessage[0]); serverOutgoingMessage.Append("World"); server.SendMessage(serverOutgoingMessage); NetMQMessage incomingClientMessage = new NetMQMessage(); client.ReceiveMessage(incomingClientMessage); Assert.AreEqual(1, incomingClientMessage.FrameCount); Assert.AreEqual("World", incomingClientMessage[0].ConvertToString()); } } } }
public void UseInvalidSignature() { // Victim var privateKey = new PrivateKey(); var peer = new Peer(privateKey.PublicKey, new IPAddress(1024L)); var dateTimeOffset = DateTimeOffset.UtcNow; var validAppProtocolVersion = new AppProtocolVersion( 1, new Bencodex.Types.Integer(0), ImmutableArray <byte> .Empty, default(Address)); var ping = new Ping(); var codec = new NetMQMessageCodec(); var netMqMessage = codec.Encode(ping, privateKey, peer, dateTimeOffset, validAppProtocolVersion) .ToArray(); // Attacker var fakePeer = new Peer(privateKey.PublicKey, new IPAddress(2048L)); var fakeMessage = codec.Encode(ping, privateKey, fakePeer, dateTimeOffset, validAppProtocolVersion) .ToArray(); var frames = new NetMQMessage(); frames.Push(netMqMessage[4]); frames.Push(netMqMessage[3]); frames.Push(netMqMessage[2]); frames.Push(fakeMessage[1]); frames.Push(netMqMessage[0]); Assert.Throws <InvalidMessageException>(() => { codec.Decode( frames, true, (i, p, v) => { }, TimeSpan.FromSeconds(1)); }); }
private NetMQMessage OnReceived(NetMQMessage request) { var ret = new NetMQMessage(); var selector = request.Pop(); try { switch (selector.ConvertToString()) { case "AddEntry": { var entries = request.UnpackMessageList <FuzzyWordEntry>(FuzzyWordEntry.Parser.ParseDelimitedFrom); var methodResult = AddEntry(entries); ret.Append(methodResult); break; } case "FuzzyQuery": { var phrases = request.UnpackMessageList <FuzzyCheck>(FuzzyCheck.Parser.ParseDelimitedFrom); var methodResult = FuzzyQuery(phrases); ret.PackMessageList <FuzzyQueryResponse>(methodResult);; break; } default: throw new Exception($"Unexpected selector - {selector}"); } } catch (Exception e) { L.Trace($"{selector} caused an exception"); L.Exception(e); ret.AppendEmptyFrame(); ret.Append($"{selector} caused an exception - '{e.Message}' check server logs for more details"); } return(ret); }
private async Task <XtResult <TResult> > DoRequestAsync <T, TResult>(T request) where T : class, new() where TResult : class { const string operation = "request"; _configuration.Logger.Log(new DebugLogMsg($"Send Request<{typeof(T)}, {typeof(TResult)}> to Address - {_configuration.Address()}")); using var rqSocket = new RequestSocket(); rqSocket.Connect(_configuration.Address()); var message = new RequestReplyMessage <T>(_configuration, request); return(await Task.Run(() => { // the request to be send with timeout bool rqDidNotTimeOut = rqSocket.TrySendMultipartMessage(_configuration.TimeOut, message); if (!rqDidNotTimeOut) { return XtResult <TResult> .Failed(new TimeoutException($"Request<{typeof(T)}, {typeof(TResult)}> timed out"), operation); } _configuration.Logger.Log(new DebugLogMsg($"successfully sent [Request:{typeof(T)}] and waiting for response [Response:{typeof(TResult)}]")); // wait for the response with timeout var response = new NetMQMessage(); bool noTimeOut = rqSocket.TryReceiveMultipartMessage(_configuration.TimeOut, ref response, expectedFrameCount: 3); if (!noTimeOut) { return XtResult <TResult> .Failed(new TimeoutException($"Request<{typeof(T)}, {typeof(TResult)}> timed out"), operation); } _configuration.Logger.Log(new DebugLogMsg($"received Response [Response:{typeof(TResult)}]")); // parse the response and return the result var xtResult = response.ParseRqRepMessage <TResult>(_configuration); return xtResult.IsSuccess ? XtResult <TResult> .Success(xtResult.GetResult(), operation) : XtResult <TResult> .Failed(xtResult.Exception, operation); })); }
private void HandleAuthenticateUser(NetMQMessage message) { Message <UserMessage> userMessage = new Message <UserMessage>(message); if (!Validation.IsEmailValid(userMessage.Data.Email)) { SendErrorMessage("Email or password are not valid!", ErrorCode.IncorrectEmailOrPassword, userMessage.Id); } if (!Validation.IsPasswordValid(userMessage.Data.Password)) { SendErrorMessage("Email or password are not valid!", ErrorCode.IncorrectEmailOrPassword, userMessage.Id); } var email = userMessage.Data.Email; if (_userRepository.CheckIfExists(email)) { var registeredUser = _userRepository.GetUserByEmail(userMessage.Data.Email); if (registeredUser.Password == HashHelper.ComputeHash(userMessage.Data.Password)) { Message <TokenMessage> tokenMessage = new Message <TokenMessage>("Response"); tokenMessage.Id = userMessage.Id; tokenMessage.Data.Token = _tokenManager.GenerateToken(registeredUser.Id); if (!tokenEmailPairs.ContainsKey(tokenMessage.Data.Token)) { tokenEmailPairs.Add(tokenMessage.Data.Token, userMessage.Data.Email); } NetMQMessage msg = tokenMessage.ToNetMQMessage(); SendMessage(msg); return; } } SendErrorMessage("Email or password are not valid!", ErrorCode.IncorrectEmailOrPassword, userMessage.Id); }
/// <summary> /// Try to send request message and return the response as a message, or return null if not successful /// </summary> /// <param name="address">a string denoting the address to connect to</param> /// <param name="requestMessage">The request message</param> /// <param name="numTries">The number of times to try</param> /// <param name="requestTimeout">The timeout for each request</param> /// <param name="progressPublisher">Report topics: Failure, Retry, Send, Success</param> /// <returns>the response message, or null if not successful</returns> public static NetMQMessage RequestResponseMultipartMessageWithRetry([NotNull] string address, [NotNull] NetMQMessage requestMessage, int numTries, TimeSpan requestTimeout, PublisherSocket progressPublisher = null) { var responseMessage = new NetMQMessage(); while (numTries-- > 0) { using (var requestSocket = new RequestSocket(address)) { if (progressPublisher != null) { progressPublisher.SendFrame(ProgressTopic.Send.ToString()); } requestSocket.SendMultipartMessage(requestMessage); if (requestSocket.TryReceiveMultipartMessage(requestTimeout, ref responseMessage)) { if (progressPublisher != null) { progressPublisher.SendFrame(ProgressTopic.Success.ToString()); } return(responseMessage); } if (progressPublisher != null) { progressPublisher.SendFrame(ProgressTopic.Retry.ToString()); } } } if (progressPublisher != null) { progressPublisher.SendFrame(ProgressTopic.Failure.ToString()); } return(null); }
/// <summary> /// usage: MDPServiceDiscoveryClientExample [-v] /// /// implements a MDPClient API usage with Service Discovery /// </summary> 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(); }