protected override void EstablishContext()
		{
			base.EstablishContext();

			_ping = new PingMessage();
			_future = new FutureMessage<PingMessage, Guid>(_ping.CorrelationId);

			_unsubscribe = RemoteBus.SubscribeHandler<PingMessage>(message => { _future.Set(message); });


			RemoteBus.ShouldHaveRemoteSubscriptionFor<PingMessage>();

			//LocalBus.ShouldHaveRemoteSubscriptionFor<PingMessage>();

			Trace.WriteLine("LocalBus");

			LocalBus.OutboundPipeline.Trace();

			Trace.WriteLine("RemoteBus");

			RemoteBus.OutboundPipeline.Trace();


			LocalBus.Publish(_ping);
		}
Ejemplo n.º 2
0
		public void The_pipeline_should_have_insertable_items()
		{
			// two consumers, one for each type of message

			IndiscriminantConsumer<PingMessage> pingConsumer = new IndiscriminantConsumer<PingMessage>();
			IndiscriminantConsumer<PongMessage> pongConsumer = new IndiscriminantConsumer<PongMessage>();

			UnsubscribeAction pingToken = _pipeline.Subscribe(pingConsumer);
			UnsubscribeAction pongToken = _pipeline.Subscribe(pongConsumer);

			PipelineViewer.Trace(_pipeline);

			PingMessage pingMessage = new PingMessage();
			PongMessage pongMessage = new PongMessage();

			_pipeline.Dispatch(pingMessage, accept => true);
			_pipeline.Dispatch(pongMessage, accept => true);

			Assert.AreEqual(pingMessage, pingConsumer.Consumed);
			Assert.AreEqual(pongMessage, pongConsumer.Consumed);

			pingToken();
			pongToken();

			PipelineViewer.Trace(_pipeline);
		}
		public void A_response_should_be_published_if_no_reply_address_is_specified()
		{
			var ping = new PingMessage();

			var otherConsumer = new TestMessageConsumer<PongMessage>();
			RemoteBus.SubscribeInstance(otherConsumer);

			var consumer = new TestCorrelatedConsumer<PongMessage, Guid>(ping.CorrelationId);
			LocalBus.SubscribeInstance(consumer);

			var pong = new FutureMessage<PongMessage>();

			RemoteBus.SubscribeHandler<PingMessage>(message =>
				{
					pong.Set(new PongMessage(message.CorrelationId));

					RemoteBus.Context().Respond(pong.Message);
				});

			LocalBus.Publish(ping);

			pong.IsAvailable(8.Seconds()).ShouldBeTrue("No pong generated");

			consumer.ShouldHaveReceivedMessage(pong.Message, 8.Seconds());
			otherConsumer.ShouldHaveReceivedMessage(pong.Message, 8.Seconds());
		}
Ejemplo n.º 4
0
        public void A_response_should_be_sent_directly_if_a_reply_address_is_specified()
        {
            var ping = new PingMessage();

            var otherConsumer = new TestMessageConsumer<PongMessage>();
            RemoteBus.SubscribeInstance(otherConsumer);

            var consumer = new TestCorrelatedConsumer<PongMessage, Guid>(ping.CorrelationId);
            LocalBus.SubscribeInstance(consumer);

            var pong = new FutureMessage<PongMessage>();

            RemoteBus.SubscribeHandler<PingMessage>(message =>
                {
                    pong.Set(new PongMessage(message.CorrelationId));

                    RemoteBus.Context().Respond(pong.Message);
                });

            RemoteBus.ShouldHaveRemoteSubscriptionFor<PongMessage>();
            LocalBus.ShouldHaveRemoteSubscriptionFor<PongMessage>();
            LocalBus.ShouldHaveRemoteSubscriptionFor<PingMessage>();

            LocalBus.Publish(ping, context => context.SendResponseTo(LocalBus));

            Assert.IsTrue(pong.IsAvailable(8.Seconds()), "No pong generated");

            consumer.ShouldHaveReceivedMessage(pong.Message, 8.Seconds());
            otherConsumer.ShouldNotHaveReceivedMessage(pong.Message, 1.Seconds());
        }
Ejemplo n.º 5
0
		public void A_response_should_be_published_if_no_reply_address_is_specified()
		{
			PingMessage ping = new PingMessage();

			TestMessageConsumer<PongMessage> otherConsumer = new TestMessageConsumer<PongMessage>();
			RemoteBus.Subscribe(otherConsumer);

			TestCorrelatedConsumer<PongMessage, Guid> consumer = new TestCorrelatedConsumer<PongMessage, Guid>(ping.CorrelationId);
			LocalBus.Subscribe(consumer);

			FutureMessage<PongMessage> pong = new FutureMessage<PongMessage>();

			RemoteBus.Subscribe<PingMessage>(message =>
				{
					pong.Set(new PongMessage(message.CorrelationId));

					CurrentMessage.Respond(pong.Message);
				});

			LocalBus.Publish(ping);

			Assert.IsTrue(pong.IsAvailable(3.Seconds()), "No pong generated");

			consumer.ShouldHaveReceivedMessage(pong.Message, 3.Seconds());
			otherConsumer.ShouldHaveReceivedMessage(pong.Message, 1.Seconds());
		}
        public void Should_ignore_a_response_that_was_not_for_us()
        {
            var pongReceived = new FutureMessage<PongMessage>();
            var pingReceived = new FutureMessage<PingMessage>();
            var badResponse = new FutureMessage<PongMessage>();

            LocalBus.SubscribeHandler<PongMessage>(pongReceived.Set);

            RemoteBus.SubscribeContextHandler<PingMessage>(x =>
                {
                    pingReceived.Set(x.Message);
                    RemoteBus.Publish(new PongMessage {TransactionId = x.Message.TransactionId});
                });
            LocalBus.ShouldHaveSubscriptionFor<PingMessage>();

            var ping = new PingMessage();

            TimeSpan timeout = 8.Seconds();

            Assert.Throws<RequestTimeoutException>(() =>
                {
                    RemoteBus.Endpoint.SendRequest(ping, LocalBus, x =>
                        {
                            x.Handle<PongMessage>(badResponse.Set);

                            x.SetTimeout(timeout);
                        });
                });

            pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received");
            pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received");
            badResponse.IsAvailable(2.Seconds()).ShouldBeFalse("Should not have received a response");
        }
        public void Should_support_send_as_well()
        {
            var pongReceived = new FutureMessage<PongMessage>();
            var pingReceived = new FutureMessage<PingMessage>();

            RemoteBus.SubscribeContextHandler<PingMessage>(x =>
                {
                    pingReceived.Set(x.Message);
                    x.Respond(new PongMessage {TransactionId = x.Message.TransactionId});
                });
            LocalBus.ShouldHaveSubscriptionFor<PingMessage>();

            var ping = new PingMessage();

            TimeSpan timeout = 8.Seconds();

            RemoteBus.Endpoint.SendRequest(ping, LocalBus, x =>
                {
                    x.Handle<PongMessage>(message =>
                        {
                            message.TransactionId.ShouldEqual(ping.TransactionId,
                                "The response correlationId did not match");
                            pongReceived.Set(message);
                        });

                    x.SetTimeout(timeout);
                });

            pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received");
            pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received");
        }
		public void Should_use_a_clean_syntax_following_standard_conventions()
		{
			var pongReceived = new FutureMessage<PongMessage>();
			var pingReceived = new FutureMessage<PingMessage>();

			RemoteBus.SubscribeHandler<PingMessage>(x =>
				{
					pingReceived.Set(x);
					RemoteBus.MessageContext<PingMessage>().Respond(new PongMessage(x.CorrelationId));
				});

			var ping = new PingMessage();

			var timeout = 8.Seconds();

			LocalBus.PublishRequest(ping, x =>
				{
					x.Handle<PongMessage>(message =>
						{
							message.CorrelationId.ShouldEqual(ping.CorrelationId, "The response correlationId did not match");
							pongReceived.Set(message);
						});

					x.SetTimeout(timeout);
				});

			pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received");
			pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received");
		}
		public void Should_support_the_asynchronous_programming_model()
		{
			var pongReceived = new FutureMessage<PongMessage>();
			var pingReceived = new FutureMessage<PingMessage>();
			var callbackCalled = new FutureMessage<IAsyncResult>();

			RemoteBus.SubscribeHandler<PingMessage>(x =>
				{
					pingReceived.Set(x);
					RemoteBus.MessageContext<PingMessage>().Respond(new PongMessage(x.CorrelationId));
				});

			var ping = new PingMessage();

			var timeout = 8.Seconds();

			LocalBus.BeginPublishRequest(ping, callbackCalled.Set, null, x =>
				{
					x.Handle<PongMessage>(message =>
						{
							message.CorrelationId.ShouldEqual(ping.CorrelationId, "The response correlationId did not match");
							pongReceived.Set(message);
						});

					x.SetTimeout(timeout);
				});

			callbackCalled.IsAvailable(timeout).ShouldBeTrue("The callback was not called");

			LocalBus.EndRequest(callbackCalled.Message);

			pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received");
			pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received");
		}
Ejemplo n.º 10
0
		private void VerifyMessageHeaderIsPassed(Action<IOutboundMessage> setHeaderAction, Action<IInboundMessageHeaders> checkHeaderAction)
		{
			byte[] data;
			var serializer = new XmlMessageSerializer();

			OutboundMessage.Set(setHeaderAction);

			var message = new PingMessage();

			using (MemoryStream output = new MemoryStream())
			{
				serializer.Serialize(output, message);

				data = output.ToArray();
			}

			Trace.WriteLine(OutboundMessage.Headers.MessageType);

			Trace.WriteLine(Encoding.UTF8.GetString(data));

			using (MemoryStream input = new MemoryStream(data))
			{
				serializer.Deserialize(input);

				checkHeaderAction(CurrentMessage.Headers);
			}
		}
        public async Task Should_be_received_properly()
        {
            object message = new PingMessage();
            await Bus.Publish(message);

            await _received;
        }
		public void A_clean_method_of_a_request_reply_should_be_possible()
		{
			var ponged = new FutureMessage<PongMessage>();

			RemoteBus.SubscribeHandler<PingMessage>(x =>
				{
					// timing issue here it seems, but that's what Respond() is for, to RESPOND to messages
					// and not publish responses
					RemoteBus.ShouldHaveSubscriptionFor<PongMessage>();

					RemoteBus.Publish(new PongMessage(x.CorrelationId));
				});

			LocalBus.ShouldHaveSubscriptionFor<PingMessage>();

			var ping = new PingMessage();


			LocalBus.PublishRequest(ping, x =>
				{
					x.Handle<PongMessage>(message =>
						{
							message.CorrelationId.ShouldEqual(ping.CorrelationId);
							ponged.Set(message);
						});

					x.HandleTimeout(8.Seconds(), () => { });
				});

			ponged.IsAvailable(8.Seconds()).ShouldBeTrue("No ping response received");
		}
Ejemplo n.º 13
0
        public async Task Should_end_well()
        {
            var timer = Stopwatch.StartNew();

            Task[] publishers = new Task[100*1000];
            Parallel.For(0, 100, i =>
            {
                var offset = i * 1000;

                for (int j = 0; j < 1000; j++)
                {
                    var ping = new PingMessage();
                    var task = Bus.Publish(ping);
                    publishers[offset + j] = task;
                }
            });

            var published = timer.Elapsed;

            await Task.WhenAll(publishers);

            var confirmed = timer.Elapsed;

            Console.WriteLine("Published {0} messages in {1}ms ({2:F0}/s)", 100 * 1000, published.TotalMilliseconds, 100L * 1000L * 1000L / published.TotalMilliseconds);

            Console.WriteLine("Confirmed {0} messages in {1}ms ({2:F0}/s)", 100 * 1000, confirmed.TotalMilliseconds, 100L * 1000L * 1000L / confirmed.TotalMilliseconds);

            await _completed.Task;

            var completed = timer.Elapsed;

            Console.WriteLine("Completed {0} messages in {1}ms ({2:F0}/s)", 100 * 1000, completed.TotalMilliseconds, 100L * 1000L * 1000L / completed.TotalMilliseconds);
        }
Ejemplo n.º 14
0
 public async Task Setup()
 {
     var message = new PingMessage();
     await InputQueueSendEndpoint.Send(message, context =>
     {
         context.SetSessionId(message.CorrelationId.ToString());
     });
 }
 public async Task Setup()
 {
     _pingMessage = new PingMessage();
     _pingMessage2 = new PingMessage();
     await InputQueueSendEndpoint.Send(_pingMessage, Pipe.Execute<SendContext<PingMessage>>(context =>
     {
         context.CorrelationId = _correlationId;
     }));
 }
Ejemplo n.º 16
0
		public void It_should_be_received_by_a_component()
		{
			RemoteBus.SubscribeConsumer<TestMessageConsumer<PingMessage>>();

			PingMessage message = new PingMessage();
			LocalBus.Publish(message);

			TestConsumerBase<PingMessage>.AnyShouldHaveReceivedMessage(message, _timeout);
		}
Ejemplo n.º 17
0
        public async Task Should_include_a_correlation_id()
        {
            var pingMessage = new PingMessage();
            await Bus.Publish(pingMessage);

            var context = await _handled;

            context.CorrelationId.HasValue.ShouldBe(true);
            context.CorrelationId.Value.ShouldBe(pingMessage.CorrelationId);
        }
        public async Task Should_be_received_properly()
        {
            var message = new PingMessage();
            await Bus.Publish(message, Pipe.New<PublishContext>(x => x.UseExecute(v => v.RequestId = _requestId)));

            ConsumeContext<PingMessage> context = await _received;

            context.RequestId.HasValue.ShouldBe(true);
            context.RequestId.Value.ShouldBe(_requestId);
        }
Ejemplo n.º 19
0
		public void It_should_be_received_by_one_subscribed_consumer()
		{
			TestMessageConsumer<PingMessage> consumer = new TestMessageConsumer<PingMessage>();
			RemoteBus.SubscribeInstance(consumer);

			PingMessage message = new PingMessage();
			LocalBus.Publish(message);

			consumer.ShouldHaveReceivedMessage(message, _timeout);
		}
Ejemplo n.º 20
0
		public void A_simple_bus_should_be_able_to_subscribe_and_publish()
		{
			TestMessageConsumer<PingMessage> consumer = new TestMessageConsumer<PingMessage>();
			LocalBus.Subscribe(consumer);

			PingMessage message = new PingMessage();
			LocalBus.Publish(message);

			consumer.ShouldHaveReceivedMessage(message, 500.Milliseconds());
		}
Ejemplo n.º 21
0
		public void It_should_be_received_by_one_subscribed_consumer_on_the_same_bus()
		{
			var consumer = new TestMessageConsumer<PingMessage>();
			LocalBus.Subscribe(consumer);

			var message = new PingMessage();
			LocalBus.Publish(message);

			consumer.ShouldHaveReceivedMessage(message, _timeout);
		}
Ejemplo n.º 22
0
        public void A_simple_bus_should_be_able_to_subscribe_and_publish()
        {
            var consumer = new TestMessageConsumer<PingMessage>();
            LocalBus.SubscribeInstance(consumer);

            var message = new PingMessage();
            LocalBus.Publish(message);

            consumer.ShouldHaveReceivedMessage(message, 8.Seconds());
        }
Ejemplo n.º 23
0
 public void Setup()
 {
     Await(() =>
     {
         var message = new PingMessage();
         return InputQueueSendEndpoint.Send(message, context =>
         {
             context.SetSessionId(message.CorrelationId.ToString());
         });
     });
 }
Ejemplo n.º 24
0
        public async Task Should_include_a_correlation_id()
        {
            var pingMessage = new PingMessage();

            await InputQueueSendEndpoint.Send(pingMessage);

            var context = await _handled;

            context.CorrelationId.HasValue.ShouldBe(true);
            context.CorrelationId.Value.ShouldBe(pingMessage.CorrelationId);
        }
Ejemplo n.º 25
0
		public void It_should_be_received_by_a_component()
		{
			ObjectBuilder.Stub(x => x.GetInstance<TestMessageConsumer<PingMessage>>()).Return(new TestMessageConsumer<PingMessage>());

			RemoteBus.Subscribe<TestMessageConsumer<PingMessage>>();

			PingMessage message = new PingMessage();
			LocalBus.Publish(message);

			TestConsumerBase<PingMessage>.AnyShouldHaveReceivedMessage(message, _timeout);
		}
Ejemplo n.º 26
0
		public void It_should_be_received_by_an_interested_correlated_consumer()
		{
			PingMessage message = new PingMessage();

			TestCorrelatedConsumer<PingMessage, Guid> consumer = new TestCorrelatedConsumer<PingMessage, Guid>(message.CorrelationId);
			RemoteBus.SubscribeInstance(consumer);

			LocalBus.Publish(message);

			consumer.ShouldHaveReceivedMessage(message, _timeout);
		}
Ejemplo n.º 27
0
        public async Task Should_only_defer_up_to_the_retry_count()
        {
            var pingMessage = new PingMessage();

            var fault = SubscribeHandler<Fault<PingMessage>>(x => x.Message.Message.CorrelationId == pingMessage.CorrelationId);

            await InputQueueSendEndpoint.Send(pingMessage, x => x.FaultAddress = Bus.Address);

            ConsumeContext<Fault<PingMessage>> faultContext = await fault;

            Assert.That(_count, Is.EqualTo(3));
        }
        public void Subscribing_a_consumer_to_the_bus()
        {
            _bus = ServiceBusFactory.New(x =>
                {
                    x.ReceiveFrom("loopback://localhost/mt_test");

                    x.Subscribe(s => s.Consumer(typeof (ConsumerOf<PingMessage>), Activator.CreateInstance));
                });

            _ping = new PingMessage(Guid.NewGuid());
            _bus.Publish(_ping);
        }
Ejemplo n.º 29
0
		public void The_subscriptions_should_be_a_separate_concern_from_the_pipeline()
		{
			IndiscriminantConsumer<PingMessage> consumer = new IndiscriminantConsumer<PingMessage>();

			_pipeline.Subscribe(consumer);

			PingMessage message = new PingMessage();

			_pipeline.Dispatch(message, x => true);

			Assert.AreEqual(message, consumer.Consumed);
		}
Ejemplo n.º 30
0
		public void The_appropriate_handler_should_be_added()
		{
			IndiscriminantConsumer<PingMessage> consumer = new IndiscriminantConsumer<PingMessage>();

			_pipeline.Subscribe(consumer);

			PingMessage message = new PingMessage();

			_pipeline.Dispatch(message, x => true);

			Assert.AreEqual(message, consumer.Consumed);
		}
Ejemplo n.º 31
0
 protected Task OnPingMessageAsync(PingMessage pingMessage)
 {
     return(Task.CompletedTask);
 }
Ejemplo n.º 32
0
 public static void HandlePing(StsSession session, PingMessage ping)
 {
     session.Heartbeat.OnHeartbeat();
 }
Ejemplo n.º 33
0
        internal static void Shutdown()
        {
            if (_instance == null)
            {
                SnLog.WriteWarning("Repository shutdown has already completed.");
                return;
            }

            lock (_shutDownSync)
            {
                if (_instance == null)
                {
                    SnLog.WriteWarning("Repository shutdown has already completed.");
                    return;
                }

                SnTrace.Repository.Write("Sending a goodbye message.");

                _instance.ConsoleWriteLine();

                _instance.ConsoleWriteLine("Sending a goodbye message...");
                DistributedApplication.ClusterChannel.ClusterMemberInfo.NeedToRecover = false;
                var pingMessage = new PingMessage();
                pingMessage.Send();

                foreach (var svc in _instance.serviceInstances)
                {
                    SnTrace.Repository.Write("Shutting down {0}", svc.GetType().Name);
                    svc.Shutdown();
                }

                SnTrace.Repository.Write("Shutting down {0}", DistributedApplication.ClusterChannel.GetType().Name);
                DistributedApplication.ClusterChannel.ShutDown();

                if (Instance.BackupIndexAtTheEnd)
                {
                    SnTrace.Repository.Write("Backing up the index.");
                    if (LuceneManagerIsRunning)
                    {
                        _instance.ConsoleWriteLine("Backing up the index...");
                        SenseNet.Search.Indexing.BackupTools.SynchronousBackupIndex();
                        _instance.ConsoleWriteLine("The backup of index is finished.");
                    }
                    else
                    {
                        _instance.ConsoleWriteLine("Backing up index is skipped because Lucene was not started.");
                    }
                }

                if (LuceneManagerIsRunning)
                {
                    SnTrace.Repository.Write("Shutting down LuceneManager.");
                    SenseNet.Search.Indexing.LuceneManager.ShutDown();
                }

                SnTrace.Repository.Write("Waiting for writer lock file is released.");
                WaitForWriterLockFileIsReleased(WaitForLockFileType.OnEnd);

                var t   = DateTime.UtcNow - _instance._startupInfo.Starting;
                var msg = String.Format("Repository has stopped. Running time: {0}.{1:d2}:{2:d2}:{3:d2}", t.Days,
                                        t.Hours, t.Minutes, t.Seconds);

                SnTrace.Repository.Write(msg);
                SnTrace.Flush();

                _instance.ConsoleWriteLine(msg);
                _instance.ConsoleWriteLine();
                SnLog.WriteInformation(msg);
                _instance = null;
            }
        }
Ejemplo n.º 34
0
 public void SetUp()
 {
     Message = new PingMessage();
 }
Ejemplo n.º 35
0
        public static void ProcessingPingMessag(PingMessage message)
        {
            PingMessage pingMessage = new PingMessage(0, Agent.IdAgent);

            Agent.QueueSend.Send(pingMessage);
        }
Ejemplo n.º 36
0
 public void Handle(PingMessage message)
 {
     Console.WriteLine("I got a ping!");
 }
Ejemplo n.º 37
0
 public PongMessage Handle(PingMessage ping)
 {
     Console.WriteLine("Received ping message");
     return(new PongMessage());
 }
Ejemplo n.º 38
0
 public PongMessage Consume(PingMessage message)
 {
     return(new PongMessage());
 }
Ejemplo n.º 39
0
 protected void OnPingMessage(NetworkConnection conn, PingMessage msg)
 {
     Manager.Send(conn, new PongMessage(msg.pingTimestamp));
 }
Ejemplo n.º 40
0
 private void ServiceBuse_OnRecieve(object sender, PingMessage message)
 {
     storage.UpdateStatusAsync(message);
     new QueueSender(connectoinString, "eventsourcingqueue", serviceProvider).send(message);
     // new QueueSender(connectoinString, "statusqeue", serviceProvider).send(message);
 }
Ejemplo n.º 41
0
 private void WritePingMessage(PingMessage _, ref MessagePackWriter writer)
 {
     writer.WriteArrayHeader(1);
     writer.Write(HubProtocolConstants.PingMessageType);
 }
Ejemplo n.º 42
0
 public override Task HandlePingAsync(PingMessage pingMessage)
 {
     throw new NotSupportedException();
 }
Ejemplo n.º 43
0
 public void Handle(PingMessage message)
 {
     throw new NotSupportedException();
 }
Ejemplo n.º 44
0
 public void Consume(PingMessage message)
 {
     Show(message);
 }
Ejemplo n.º 45
0
 public abstract Task HandlePingAsync(PingMessage pingMessage);
Ejemplo n.º 46
0
 private string GetMessageId(PingMessage message) => $"ID_{message.Counter}";
Ejemplo n.º 47
0
        public Message Parse(byte[] payload)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            if (payload.Length < 24)
            {
                throw new ParseMessageException(ErrorCodes.InvalidCommandLength);
            }

            var header             = payload.Take(40); // Extract the header.
            var startStringPayload = header.Take(4);
            var network            = Networks.MainNet;

            if (startStringPayload.SequenceEqual(new byte[] { 0xf9, 0xbe, 0xb4, 0xd9 }))
            {
                network = Networks.MainNet;
            }
            else if (startStringPayload.SequenceEqual(new byte[] { 0x0b, 0x11, 0x09, 0x07 }))
            {
                network = Networks.TestNet;
            }
            else if (startStringPayload.SequenceEqual(new byte[] { 0xfa, 0xbf, 0xb5, 0xda }))
            {
                network = Networks.RegTest;
            }
            else
            {
                throw new ParseMessageException(ErrorCodes.InvalidStartString);
            }

            var commandNamePayload = header.Skip(4).Take(12).Where(b => b != 0x00).ToArray();
            var commandName        = System.Text.Encoding.ASCII.GetString(commandNamePayload);
            var ipv6 = header.Skip(16).Take(16);
            var payloadSizePayload = header.Skip(32).Take(4).ToArray();
            var payloadSize        = BitConverter.ToInt32(payloadSizePayload, 0);
            var checkSum           = header.Skip(36).Take(4);

            byte[] contentPayload = null;
            if (payloadSize > 0)
            {
                contentPayload = payload.Skip(40).Take(payloadSize).ToArray();
                SHA256 mySHA256    = SHA256.Create();
                var    newCheckSum = mySHA256.ComputeHash(mySHA256.ComputeHash(contentPayload)).Take(4);
                if (!newCheckSum.SequenceEqual(checkSum))
                {
                    throw new ParseMessageException(ErrorCodes.InvalidChecksum);
                }
            }
            else if (!checkSum.SequenceEqual(new byte[] { 0x5d, 0xf6, 0xe0, 0xe2 }))
            {
                throw new ParseMessageException(ErrorCodes.InvalidChecksum);
            }

            if (!Constants.MessageNameLst.Contains(commandName))
            {
                throw new ParseMessageException(ErrorCodes.InvalidCommandName);
            }

            Message message = null;

            if (commandName == Constants.MessageNames.Ping)
            {
                var nonce = BitConverter.ToUInt64(contentPayload, 0);
                message = new PingMessage(nonce, network);
            }
            else if (commandName == Constants.MessageNames.Addr)
            {
                message = AddrMessage.Deserialize(contentPayload, network);
            }
            else if (commandName == Constants.MessageNames.Version)
            {
                message = VersionMessage.Deserialize(contentPayload, network);
            }
            else if (commandName == Constants.MessageNames.Verack)
            {
                message = new VerackMessage(network);
            }
            else if (commandName == Constants.MessageNames.GetAddr)
            {
                message = new GetAddressMessage(network);
            }
            else if (commandName == Constants.MessageNames.Inventory)
            {
                message = InventoryMessage.Deserialize(contentPayload, network);
            }
            else if (commandName == Constants.MessageNames.Transaction)
            {
                message = TransactionMessage.Deserialize(contentPayload, network, Transactions.TransactionTypes.NoneCoinbase);
            }
            else if (commandName == Constants.MessageNames.Pong)
            {
                var nonce = BitConverter.ToUInt64(contentPayload, 0);
                message = new PongMessage(nonce, network);
            }
            else if (commandName == Constants.MessageNames.MemPool)
            {
                message = new MemPoolMessage(network);
            }
            else if (commandName == Constants.MessageNames.GetData)
            {
                message = GetDataMessage.Deserialize(contentPayload, network);
            }
            else if (commandName == Constants.MessageNames.Block)
            {
                message = BlockMessage.Deserialize(contentPayload, network);
            }
            else if (commandName == Constants.MessageNames.GetBlocks)
            {
                message = GetBlocksMessage.Deserialize(contentPayload, network);
            }
            else if (commandName == Constants.MessageNames.NotFound)
            {
                message = NotFoundMessage.Deserialize(contentPayload, network);
            }

            message.MessageHeader.Ipv6 = ipv6.ToArray();
            return(message);
        }
Ejemplo n.º 48
0
        /// <summary> Parses the Replay.Messages.Events file. </summary>
        /// <param name="buffer"> Buffer containing the contents of the replay.messages.events file. </param>
        /// <returns> A list of messages parsed from the buffer. </returns>
        public static void Parse(Replay replay, byte[] buffer)
        {
            if (buffer.Length <= 1)
            {
                // Chat has been removed from this replay
                return;
            }

            var ticksElapsed = 0;

            using (var stream = new MemoryStream(buffer))
            {
                var bitReader = new Streams.BitReader(stream);

                while (!bitReader.EndOfStream)
                {
                    var message = new Message();

                    ticksElapsed     += (int)bitReader.Read(6 + (bitReader.Read(2) << 3));
                    message.Timestamp = new TimeSpan(0, 0, (int)Math.Round(ticksElapsed / 16.0));

                    var playerIndex = (int)bitReader.Read(5);
                    if (playerIndex != 16)
                    {
                        message.MessageSender = replay.ClientListByUserID[playerIndex];
                        message.PlayerIndex   = playerIndex;
                    }

                    message.MessageEventType = (MessageEventType)bitReader.Read(4);
                    switch (message.MessageEventType)
                    {
                    case MessageEventType.SChatMessage:
                    {
                        ChatMessage chatMessage = new ChatMessage();

                        chatMessage.MessageTarget = (MessageTarget)bitReader.Read(3);                                  // m_recipient (the target)
                        chatMessage.Message       = Encoding.UTF8.GetString(bitReader.ReadBlobPrecededWithLength(11)); // m_string

                        message.ChatMessage = chatMessage;
                        replay.Messages.Add(message);
                        break;
                    }

                    case MessageEventType.SPingMessage:
                    {
                        PingMessage pingMessage = new PingMessage();

                        pingMessage.MessageTarget = (MessageTarget)bitReader.Read(3);         // m_recipient (the target)

                        pingMessage.XCoordinate = bitReader.ReadInt32() - (-2147483648);      // m_point x
                        pingMessage.YCoordinate = bitReader.ReadInt32() - (-2147483648);      // m_point y

                        message.PingMessage = pingMessage;
                        replay.Messages.Add(message);
                        break;
                    }

                    case MessageEventType.SLoadingProgressMessage:
                    {
                        // can be used to keep track of how fast/slow players are loading
                        // also includes players who are reloading the game
                        var progress = bitReader.ReadInt32() - (-2147483648);         // m_progress
                        break;
                    }

                    case MessageEventType.SServerPingMessage:
                    {
                        break;
                    }

                    case MessageEventType.SReconnectNotifyMessage:
                    {
                        bitReader.Read(2);         // m_status; is either a 1 or a 2
                        break;
                    }

                    case MessageEventType.SPlayerAnnounceMessage:
                    {
                        PlayerAnnounceMessage announceMessage = new PlayerAnnounceMessage();

                        announceMessage.AnnouncementType = (AnnouncementType)bitReader.Read(2);

                        switch (announceMessage.AnnouncementType)
                        {
                        case AnnouncementType.None:
                        {
                            break;
                        }

                        case AnnouncementType.Ability:
                        {
                            AbilityAnnouncment ability = new AbilityAnnouncment();
                            ability.AbilityLink  = bitReader.ReadInt16();               // m_abilLink
                            ability.AbilityIndex = (int)bitReader.Read(5);              // m_abilCmdIndex
                            ability.ButtonLink   = bitReader.ReadInt16();               // m_buttonLink

                            announceMessage.AbilityAnnouncement = ability;
                            break;
                        }

                        case AnnouncementType.Behavior:            // no idea what triggers this
                        {
                            bitReader.ReadInt16();                 // m_behaviorLink
                            bitReader.ReadInt16();                 // m_buttonLink
                            break;
                        }

                        case AnnouncementType.Vitals:
                        {
                            VitalAnnouncment vital = new VitalAnnouncment();
                            vital.VitalType = (VitalType)(bitReader.ReadInt16() - (-32768));

                            announceMessage.VitalAnnouncement = vital;
                            break;
                        }

                        default:
                            throw new NotImplementedException();
                        }

                        if (replay.ReplayBuild > 45635)
                        {
                            // m_announceLink
                            bitReader.ReadInt16();
                        }

                        bitReader.ReadInt32();         // m_otherUnitTag
                        bitReader.ReadInt32();         // m_unitTag

                        message.PlayerAnnounceMessage = announceMessage;
                        replay.Messages.Add(message);
                        break;
                    }

                    default:
                        throw new NotImplementedException();
                    }

                    bitReader.AlignToByte();
                }
            }
        }
Ejemplo n.º 49
0
 public override Task HandlePingAsync(PingMessage pingMessage)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 50
0
    /*
     * used to send messages
     *<playerName -> peerToPeerConnection>
     */


    private void HandlePingMessage(PingMessage pingMessage)
    {
        pings[pingMessage.receiver] = pingMessage;
    }
 public override Task HandlePingAsync(PingMessage pingMessage)
 {
     return(Task.CompletedTask);
 }
Ejemplo n.º 52
0
 public PongMessage Handle(PingMessage message)
 {
     return(new PongMessage());
 }
Ejemplo n.º 53
0
 public void Ping(Envelope envelope, PingMessage message)
 {
 }
Ejemplo n.º 54
0
    void OnEvent(byte eventCode, object content, int senderId)
    {
        int i;
        BaseObjectMessage baseObjectMessage;
        PlayerObject      playerObject     = null;
        PlayerController  playerController = null;

        //Debug.Log("RECEIVE EVENT[" + eventCode + "] from [" + senderId + "]");
        switch (eventCode)
        {
        case 1:
            baseObjectMessage = new BaseObjectMessage();
            baseObjectMessage.Unpack((byte[])content);
            remoteTimestamp = baseObjectMessage.timemark;
            gameNetwork.ClientInit();
            gameNetwork.playerId = baseObjectMessage.id;
            Debug.Log("INITIALIZE PLAYER ID: " + gameNetwork.playerId);
            /* duplicate for GameNetwork RpcSpawnObject case PLAYER */
            playerObject = (PlayerObject)gameNetwork.location.GetObject(gameNetwork.playerId);
            if (playerObject != null)
            {
                camera.transform.position = playerObject.position * 100.0f + Vector3.up * 20.0f;
                if (gameNetwork.playerId == 1)
                {
                    camera.transform.eulerAngles = new Vector3(camera.transform.eulerAngles.x, 180.0f, camera.transform.eulerAngles.z);
                }
            }
            playerObject = (PlayerObject)gameNetwork.location.GetObject(gameNetwork.playerId == 1 ? 0 : 1);
            if (playerObject != null && playerObject.visualObject == null)
            {
                playerController                    = (Instantiate(gameNetwork.bodyPrefabs[0])).GetComponent <PlayerController>();
                playerController.gameNetwork        = gameNetwork;
                playerController.obj                = playerObject;
                playerObject.visualObject           = playerController;
                playerController.transform.position = playerObject.position * 100.0f;
                //playerController.transform.localScale *= 10.0f;
                if (playerObject.position.z < 0.0f)
                {
                    playerObject.visualObject.transform.Rotate(0.0f, 180.0f, 0.0f);
                }
            }
            /* */
            canvasPlay.enabled = true;

            InitializeMessage initializeMessage = new InitializeMessage();
            for (i = 1; i < AbilityButtons.Length; i++)
            {
                if (AbilityButtons[i].image.color == Color.green)
                {
                    if (initializeMessage.abilityFirstId <= -1)
                    {
                        initializeMessage.abilityFirstId = i;
                    }
                    else
                    {
                        initializeMessage.abilitySecondId = i;
                    }
                }
            }
            gameNetwork.myMissileId     = armedMissile.GetCurrentMissile();
            initializeMessage.missileId = gameNetwork.myMissileId;
            for (i = 1; i < VenomButtons.Length; i++)
            {
                if (VenomButtons[i].image.color == Color.green)
                {
                    initializeMessage.venomId = i;
                }
            }
            PhotonNetwork.networkingPeer.OpCustom((byte)1, new Dictionary <byte, object> {
                { 245, initializeMessage.Pack() }
            }, true);

            break;

        case 2:
            SpawnObjectMessage spawnObjectMessage = new SpawnObjectMessage();
            spawnObjectMessage.Unpack((byte[])content);
            //Debug.Log(Time.fixedTime + " Spawn." + spawnObjectMessage.objectType + " [" + spawnObjectMessage.id + "]");
            spawnObjectMessage.eventCode = eventCode;
            delayedMessages.AddLast(spawnObjectMessage);
            //gameNetwork.RpcSpawnObject(spawnObjectMessage.id, spawnObjectMessage.objectType, spawnObjectMessage.newPosition, spawnObjectMessage.newFloat, spawnObjectMessage.visualId);
            break;

        case 3:
            DestroyObjectMessage destroyObjectMessage = new DestroyObjectMessage();
            destroyObjectMessage.Unpack((byte[])content);
            //Debug.Log(Time.fixedTime + " Destroy [" + destroyObjectMessage.id + "]: " + destroyObjectMessage.objectId);
            destroyObjectMessage.eventCode = eventCode;
            delayedMessages.AddLast(destroyObjectMessage);
            //gameNetwork.RpcDestroyObject(destroyObjectMessage.id);
            break;

        case 4:
            MoveObjectMessage moveObjectMessage = new MoveObjectMessage();
            moveObjectMessage.Unpack((byte[])content);
            //Debug.Log(Time.fixedTime + " Move [" + moveObjectMessage.id + "]");
            moveObjectMessage.eventCode = eventCode;
            delayedMessages.AddLast(moveObjectMessage);
            //gameNetwork.RpcMoveObject(moveObjectMessage.id, moveObjectMessage.newPosition, moveObjectMessage.newFloat, moveObjectMessage.timestamp);
            break;

        case 5:
            UpdatePlayerMessage updatePlayerMessage = new UpdatePlayerMessage();
            updatePlayerMessage.Unpack((byte[])content);
            //Debug.Log("Player[" + updatePlayerMessage.id + "] health: " + updatePlayerMessage.newHealth + " ; stamina: " + updatePlayerMessage.newStamina);
            gameNetwork.RpcUpdatePlayer(updatePlayerMessage.id, updatePlayerMessage.newHealth, updatePlayerMessage.newStamina, updatePlayerMessage.newStaminaConsumption);
            break;

        case 6:
            gameNetwork.RpcRearmMissile();
            break;

        case 7:
            baseObjectMessage = new BaseObjectMessage();
            baseObjectMessage.Unpack((byte[])content);
            gameNetwork.RpcFlashPlayer(baseObjectMessage.id);
            break;

        case 8:
            GameOverMessage gameOverMessage = new GameOverMessage();
            gameOverMessage.Unpack((byte[])content);
            gameNetwork.RpcGameOver(gameOverMessage.winner, gameOverMessage.time, gameOverMessage.damage, gameOverMessage.wound);

            gameNetwork                = GameObject.Instantiate(gameNetworkPrefab).GetComponent <GameNetwork>();
            gameNetwork.camera         = camera;
            gameNetwork.gameMatchMaker = this;
            gameNetwork.isServer       = false;
            gameNetwork.isLocal        = false;

            break;

        case 9:
            SetAbilityMessage setAbilityMessage = new SetAbilityMessage();
            setAbilityMessage.Unpack((byte[])content);
            gameNetwork.RpcSetAbility(setAbilityMessage.id, setAbilityMessage.value);
            break;

        case 10:
            NoticeMessage noticeMessage = new NoticeMessage();
            noticeMessage.Unpack((byte[])content);
            //Debug.Log("GET NOTICE MESSAGE. timemark: " + noticeMessage.timemark + " ; numericValue: " + noticeMessage.numericValue);
            noticeMessage.eventCode = eventCode;
            delayedMessages.AddLast(noticeMessage);
            break;

        case 11:
            baseObjectMessage = new BaseObjectMessage();
            baseObjectMessage.Unpack((byte[])content);
            Debug.Log("RECEIVE FLASH PASSIVE ABILITY. timemark: " + baseObjectMessage.timemark);
            baseObjectMessage.eventCode = eventCode;
            delayedMessages.AddLast(baseObjectMessage);
            break;

        case 12:
            baseObjectMessage = new BaseObjectMessage();
            baseObjectMessage.Unpack((byte[])content);
            //Debug.Log("FLASH OBSTRUCTION[" + baseObjectMessage.id + "]. timemark: " + baseObjectMessage.timemark);
            gameNetwork.RpcFlashObstruction(baseObjectMessage.id);
            break;

        case 13:
            VisualEffectMessage visualEffectMessage = new VisualEffectMessage();
            visualEffectMessage.Unpack((byte[])content);
            Debug.Log("VISUAL EFFECT [" + visualEffectMessage.id + "]. targetId: " + visualEffectMessage.targetId);
            visualEffectMessage.eventCode = eventCode;
            delayedMessages.AddLast(visualEffectMessage);
            break;

        case 14:
            PingMessage pingMessage = new PingMessage();
            PingMessage newPingMessage;
            pingMessage.Unpack((byte[])content);
            if (pingMessage.time == 0.0f)
            {
                newPingMessage = new PingMessage(remoteTimestamp, pingMessage.timemark);
                PhotonNetwork.networkingPeer.OpCustom((byte)4, new Dictionary <byte, object> {
                    { 245, newPingMessage.Pack() }
                }, true);
            }
            else
            {
                remoteTimestamp = pingMessage.timemark + pingMessage.time / 2.0f;
            }
            break;
        }
    }
Ejemplo n.º 55
0
 protected Task OnPingMessageAsync(PingMessage pingMessage)
 {
     return(_serviceMessageHandler.HandlePingAsync(pingMessage));
 }
Ejemplo n.º 56
0
 public static void HandlePingMessage(SimpleClient client, PingMessage message)
 {
     //SendLoginMessage(client, message.unknown);
 }
Ejemplo n.º 57
0
 public void send(PingMessage message)
 {
     serviceBus.Send(message);
 }
        public void It_should_be_ignored_if_there_are_no_consumers()
        {
            PingMessage message = new PingMessage();

            LocalBus.Publish(message);
        }
Ejemplo n.º 59
0
 public void Consume(PingMessage message)
 {
     // do stuff using IMyService with the PingMessage
     // input
 }
Ejemplo n.º 60
0
 private void Echo(PingMessage message)
 {
     Console.WriteLine(message.Message);
 }