当前位置: 首页>>代码示例>>C#>>正文


C# Tcp.TcpPackage类代码示例

本文整理汇总了C#中EventStore.Core.Services.Transport.Tcp.TcpPackage的典型用法代码示例。如果您正苦于以下问题:C# TcpPackage类的具体用法?C# TcpPackage怎么用?C# TcpPackage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


TcpPackage类属于EventStore.Core.Services.Transport.Tcp命名空间,在下文中一共展示了TcpPackage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: when_handling_trusted_write_on_internal_service

        public void when_handling_trusted_write_on_internal_service()
        {
            ManualResetEvent waiter = new ManualResetEvent(false);
            ClientMessage.WriteEvents publishedWrite = null;
            var evnt = new Event(Guid.NewGuid(), "TestEventType", true, new byte[] { }, new byte[] { });
            var write = new TcpClientMessageDto.WriteEvents(
                Guid.NewGuid().ToString(),
                ExpectedVersion.Any,
                new[] { new TcpClientMessageDto.NewEvent(evnt.EventId.ToByteArray(), evnt.EventType, evnt.IsJson ? 1 : 0, 0, evnt.Data, evnt.Metadata) },
                false);

            var package = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), write.Serialize());
            var dummyConnection = new DummyTcpConnection();
            var publisher = InMemoryBus.CreateTest();

            publisher.Subscribe(new AdHocHandler<ClientMessage.WriteEvents>(x => {
                publishedWrite = x;
                waiter.Set();
            }));

            var tcpConnectionManager = new TcpConnectionManager(
                Guid.NewGuid().ToString(), TcpServiceType.Internal, new ClientTcpDispatcher(),
                publisher, dummyConnection, publisher, new InternalAuthenticationProvider(new Core.Helpers.IODispatcher(publisher, new NoopEnvelope()), new StubPasswordHashAlgorithm(), 1),
                TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), (man, err) => { });

            tcpConnectionManager.ProcessPackage(package);

            if (!waiter.WaitOne(TimeSpan.FromSeconds(5)))
            {
                throw new Exception("Timed out waiting for events.");
            }
            Assert.AreEqual(evnt.EventId, publishedWrite.Events.First().EventId, "Expected the published write to be the event that was sent through the tcp connection manager to be the event {0} but got {1}", evnt.EventId, publishedWrite.Events.First().EventId);
        }
开发者ID:SzymonPobiega,项目名称:EventStore,代码行数:33,代码来源:TcpConnectionManagerTests.cs

示例2: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            context.IsAsync();

            var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
            context.Log.Info("[{0}:{1}]: PING...", context.Client.Options.Ip, context.Client.Options.TcpPort);

            var connection = context.Client.CreateTcpConnection(
                context,
                (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.Pong)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }
                    context.Log.Info("[{0}:{1}]: PONG!", context.Client.Options.Ip, context.Client.Options.TcpPort);
                    conn.Close();
                    context.Success();
                },
                null,
                (typedConnection, error) =>
                    {
                        if (error == SocketError.Success)
                            context.Success();
                        else
                            context.Fail();
                    });
            connection.EnqueueSend(package.AsByteArray());
            context.WaitForCompletion();
            return true;
        }
开发者ID:jpierson,项目名称:EventStore,代码行数:32,代码来源:PingProcessor.cs

示例3: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            context.IsAsync();

            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
                    context.Log.Info("[{0}:{1}]: PING...", context.Client.Options.Ip, context.Client.Options.TcpPort);
                    conn.EnqueueSend(package.AsByteArray());
                },
                handlePackage: (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.Pong)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }
                    context.Log.Info("[{0}:{1}]: PONG!", context.Client.Options.Ip, context.Client.Options.TcpPort);
                    context.Success();
                    conn.Close();
                },
                connectionClosed: (typedConnection, error) => context.Fail(reason: "Connection was closed prematurely."));
            context.WaitForCompletion();
            return true;
        }
开发者ID:danieldeb,项目名称:EventStore,代码行数:27,代码来源:PingProcessor.cs

示例4: PingFloodWaiting

        private void PingFloodWaiting(CommandProcessorContext context, int clientsCnt, long requestsCnt)
        {
            context.IsAsync();

            var clients = new List<TcpTypedConnection<byte[]>>();
            var threads = new List<Thread>();
            var doneEvent = new ManualResetEventSlim(false);
            var clientsDone = 0;
            long all = 0;
            for (int i = 0; i < clientsCnt; i++)
            {
                var autoResetEvent = new AutoResetEvent(false);
                var client = context.Client.CreateTcpConnection(
                    context,
                    (_, __) =>
                    {
                        Interlocked.Increment(ref all);
                        autoResetEvent.Set();
                    },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
                        client.EnqueueSend(package.AsByteArray());
                        autoResetEvent.WaitOne();
                    }
                    if (Interlocked.Increment(ref clientsDone) == clientsCnt)
                    {
                        context.Success();
                        doneEvent.Set();
                    }
                }) { IsBackground = true });
            }

            var sw = Stopwatch.StartNew();
            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();
            clients.ForEach(x => x.Close());

            var reqPerSec = (all + 0.0)/sw.ElapsedMilliseconds*1000;
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).", all, sw.ElapsedMilliseconds, reqPerSec);
            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int) reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int) Math.Round(sw.Elapsed.TotalMilliseconds/all));

            if (Interlocked.Read(ref all) == requestsCnt)
                context.Success();
            else
                context.Fail();
        }
开发者ID:czcz1024,项目名称:EventStore,代码行数:59,代码来源:PingFloodWaitingProcessor.cs

示例5: UnwrapPing

 private static Message UnwrapPing(TcpPackage package, IEnvelope envelope)
 {
     var data = new byte[package.Data.Count];
     Buffer.BlockCopy(package.Data.Array, package.Data.Offset, data, 0, package.Data.Count);
     var pongMessage = new TcpMessage.PongMessage(package.CorrelationId, data);
     envelope.ReplyWith(pongMessage);
     return pongMessage;
 }
开发者ID:adbrowne,项目名称:EventStore,代码行数:8,代码来源:ClientTcpDispatcher.cs

示例6: UnwrapCommitAck

 private static StorageMessage.CommitAck UnwrapCommitAck(TcpPackage package, IEnvelope envelope)
 {
     var dto = package.Data.Deserialize<ReplicationMessageDto.CommitAck>();
     return new StorageMessage.CommitAck(package.CorrelationId,
                                         dto.LogPosition,
                                         dto.TransactionPosition,
                                         dto.FirstEventNumber,
                                         dto.LastEventNumber);
 }
开发者ID:danieldeb,项目名称:EventStore,代码行数:9,代码来源:InternalTcpDispatcher.cs

示例7: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var expectedVersion = ExpectedVersion.Any;

            if (args.Length > 0)
            {
                if (args.Length > 2)
                    return false;
                eventStreamId = args[0];
                if (args.Length == 2)
                    expectedVersion = args[1].Trim().ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[1]);
            }

            context.IsAsync();
            var sw = new Stopwatch();
            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}, L{1}]: Trying to delete event stream '{2}'...", conn.RemoteEndPoint, conn.LocalEndPoint, eventStreamId);
                    var corrid = Guid.NewGuid();
                    var deleteDto = new TcpClientMessageDto.DeleteStream(eventStreamId, expectedVersion, false);
                    var package = new TcpPackage(TcpCommand.DeleteStream, corrid, deleteDto.Serialize()).AsByteArray();
                    sw.Start();
                    conn.EnqueueSend(package);
                },
                handlePackage: (conn, pkg) =>
                {
                    sw.Stop();
                    context.Log.Info("Delete request took: {0}.", sw.Elapsed);

                    if (pkg.Command != TcpCommand.DeleteStreamCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize<TcpClientMessageDto.DeleteStreamCompleted>();
                    if (dto.Result == TcpClientMessageDto.OperationResult.Success)
                    {
                        context.Log.Info("DELETED event stream {0}.", eventStreamId);
                        PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)sw.ElapsedMilliseconds);
                        context.Success();
                    }
                    else
                    {
                        context.Log.Info("DELETION FAILED for event stream {0}: {1} ({2}).", eventStreamId, dto.Message, dto.Result);
                        context.Fail();
                    }
                    conn.Close();
                },
                connectionClosed:(connection, error) => context.Fail(reason: "Connection was closed prematurely."));

            context.WaitForCompletion();
            return true;
        }
开发者ID:jjvdangelo,项目名称:EventStore,代码行数:57,代码来源:DeleteProcessor.cs

示例8: not_authorized_with_empty_data_should_serialize_and_deserialize_correctly

        public void not_authorized_with_empty_data_should_serialize_and_deserialize_correctly()
        {
            var corrId = Guid.NewGuid();
            var refPkg = new TcpPackage(TcpCommand.BadRequest, TcpFlags.None, corrId, null, null, new byte[0]);
            var bytes = refPkg.AsArraySegment();

            var pkg = TcpPackage.FromArraySegment(bytes);
            Assert.AreEqual(TcpCommand.BadRequest, pkg.Command);
            Assert.AreEqual(TcpFlags.None, pkg.Flags);
            Assert.AreEqual(corrId, pkg.CorrelationId);
            Assert.AreEqual(null, pkg.Login);
            Assert.AreEqual(null, pkg.Password);

            Assert.AreEqual(0, pkg.Data.Count);
        }
开发者ID:danieldeb,项目名称:EventStore,代码行数:15,代码来源:core_tcp_package.cs

示例9: UnwrapReplicaSubscriptionRequest

 private ReplicationMessage.ReplicaSubscriptionRequest UnwrapReplicaSubscriptionRequest(TcpPackage package, IEnvelope envelope, TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<ReplicationMessageDto.SubscribeReplica>();
     var vnodeTcpEndPoint = new IPEndPoint(new IPAddress(dto.Ip), dto.Port);
     var lastEpochs = dto.LastEpochs.Safe().Select(x => new Epoch(x.EpochPosition, x.EpochNumber, new Guid(x.EpochId))).ToArray();
     return new ReplicationMessage.ReplicaSubscriptionRequest(package.CorrelationId,
                                                              envelope, 
                                                              connection,
                                                              dto.LogPosition,
                                                              new Guid(dto.ChunkId), 
                                                              lastEpochs,
                                                              vnodeTcpEndPoint,
                                                              new Guid(dto.MasterId), 
                                                              new Guid(dto.SubscriptionId), 
                                                              dto.IsPromotable);
 }
开发者ID:danieldeb,项目名称:EventStore,代码行数:16,代码来源:InternalTcpDispatcher.cs

示例10: UnwrapWriteEvents

        private static ClientMessage.WriteEvents UnwrapWriteEvents(TcpPackage package, IEnvelope envelope,
                                                                   IPrincipal user, string login, string password)
        {
            var dto = package.Data.Deserialize<TcpClientMessageDto.WriteEvents>();
            if (dto == null) return null;
            
            var events = new Event[dto.Events == null ? 0 : dto.Events.Length];
            for (int i = 0; i < events.Length; ++i)
            {
// ReSharper disable PossibleNullReferenceException
                var e = dto.Events[i];
// ReSharper restore PossibleNullReferenceException
                events[i] = new Event(new Guid(e.EventId), e.EventType, e.DataContentType == 1, e.Data, e.Metadata);
            }
            return new ClientMessage.WriteEvents(Guid.NewGuid(), package.CorrelationId, envelope, dto.RequireMaster,
                                                 dto.EventStreamId, dto.ExpectedVersion, events, user, login, password);
        }
开发者ID:adbrowne,项目名称:EventStore,代码行数:17,代码来源:ClientTcpDispatcher.cs

示例11: when_handling_trusted_write_on_external_service

        public void when_handling_trusted_write_on_external_service()
        {
            var package = new TcpPackage(TcpCommand.WriteEvents, TcpFlags.TrustedWrite, Guid.NewGuid(), null, null, new byte[] { });

            var dummyConnection = new DummyTcpConnection();

            var tcpConnectionManager = new TcpConnectionManager(
                Guid.NewGuid().ToString(), TcpServiceType.External, new ClientTcpDispatcher(),
                InMemoryBus.CreateTest(), dummyConnection, InMemoryBus.CreateTest(), new InternalAuthenticationProvider(new Core.Helpers.IODispatcher(InMemoryBus.CreateTest(), new NoopEnvelope()), new StubPasswordHashAlgorithm(), 1),
                TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), (man, err) => { });

            tcpConnectionManager.ProcessPackage(package);

            var data = dummyConnection.ReceivedData.Last();
            var receivedPackage = TcpPackage.FromArraySegment(data);
           
            Assert.AreEqual(receivedPackage.Command, TcpCommand.BadRequest, "Expected Bad Request but got {0}", receivedPackage.Command);
        }
开发者ID:SzymonPobiega,项目名称:EventStore,代码行数:18,代码来源:TcpConnectionManagerTests.cs

示例12: authorized_with_data_should_serialize_and_deserialize_correctly

        public void authorized_with_data_should_serialize_and_deserialize_correctly()
        {
            var corrId = Guid.NewGuid();
            var refPkg = new TcpPackage(TcpCommand.BadRequest, TcpFlags.Authenticated, corrId, "login", "pa$$", new byte[] { 1, 2, 3 });
            var bytes = refPkg.AsArraySegment();

            var pkg = TcpPackage.FromArraySegment(bytes);
            Assert.AreEqual(TcpCommand.BadRequest, pkg.Command);
            Assert.AreEqual(TcpFlags.Authenticated, pkg.Flags);
            Assert.AreEqual(corrId, pkg.CorrelationId);
            Assert.AreEqual("login", pkg.Login);
            Assert.AreEqual("pa$$", pkg.Password);

            Assert.AreEqual(3, pkg.Data.Count);
            Assert.AreEqual(1, pkg.Data.Array[pkg.Data.Offset + 0]);
            Assert.AreEqual(2, pkg.Data.Array[pkg.Data.Offset + 1]);
            Assert.AreEqual(3, pkg.Data.Array[pkg.Data.Offset + 2]);
        }
开发者ID:danieldeb,项目名称:EventStore,代码行数:18,代码来源:core_tcp_package.cs

示例13: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var package = new TcpPackage(TcpCommand.ScavengeDatabase, Guid.NewGuid(), null);
            context.Log.Info("Sending SCAVENGE request...");

            var connection = context.Client.CreateTcpConnection(
                context,
                (conn, pkg) => { },
                null,
                (typedConnection, error) =>
                {
                    if (error == SocketError.Success)
                        context.Success();
                    else
                        context.Fail();
                });
            connection.EnqueueSend(package.AsByteArray());
            connection.Close("OK");
            return true;
        }
开发者ID:thinkbeforecoding,项目名称:EventStore,代码行数:20,代码来源:ScavengeProcessor.cs

示例14: UnwrapReadStreamEventsForward

 private static ClientMessage.ReadStreamEventsForward UnwrapReadStreamEventsForward(TcpPackage package,
                                                                                    IEnvelope envelope,
                                                                                    TcpConnectionManager connection)
 {
     var dto = package.Data.Deserialize<TcpClientMessageDto.ReadStreamEventsForward>();
     if (dto == null) return null;
     return new ClientMessage.ReadStreamEventsForward(package.CorrelationId,
                                                      envelope,
                                                      dto.EventStreamId,
                                                      dto.StartIndex,
                                                      dto.MaxCount,
                                                      dto.ResolveLinkTos);
 }
开发者ID:robashton,项目名称:EventStore,代码行数:13,代码来源:ClientTcpDispatcher.cs

示例15: UnwrapTransactionStart

 private static ClientMessage.TransactionStart UnwrapTransactionStart(TcpPackage package, IEnvelope envelope)
 {
     var dto = package.Data.Deserialize<TcpClientMessageDto.TransactionStart>();
     if (dto == null) return null;
     return new ClientMessage.TransactionStart(package.CorrelationId, envelope, dto.AllowForwarding, dto.EventStreamId, dto.ExpectedVersion);
 }
开发者ID:robashton,项目名称:EventStore,代码行数:6,代码来源:ClientTcpDispatcher.cs


注:本文中的EventStore.Core.Services.Transport.Tcp.TcpPackage类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。