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


C# TcpPackage.AsByteArray方法代码示例

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


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

示例1: 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

示例2: 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

示例3: 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

示例4: 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

示例5: Execute

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

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

            context.IsAsync();

            var sw = new Stopwatch();
            var stage = Stage.AcquiringTransactionId;
            long transactionId = -1;
            var writtenEvents = 0;
            context.Client.CreateTcpConnection(
                    context,
                    connectionEstablished: conn =>
                    {
                        context.Log.Info("[{0}, L{1}]: Starting transaction...", conn.RemoteEndPoint, conn.LocalEndPoint);
                        sw.Start();
                        
                        var tranStart = new TcpClientMessageDto.TransactionStart(eventStreamId, expectedVersion, false);
                        var package = new TcpPackage(TcpCommand.TransactionStart, Guid.NewGuid(), tranStart.Serialize());
                        conn.EnqueueSend(package.AsByteArray());
                    },
                    handlePackage: (conn, pkg) =>
                    {
                        switch (stage)
                        {
                            case Stage.AcquiringTransactionId:
                            {
                                if (pkg.Command != TcpCommand.TransactionStartCompleted)
                                {
                                    context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                                    return;
                                }

                                var dto = pkg.Data.Deserialize<TcpClientMessageDto.TransactionStartCompleted>();
                                if (dto.Result != TcpClientMessageDto.OperationResult.Success)
                                {
                                    var msg = string.Format("Error while starting transaction: {0} ({1}).", dto.Message, dto.Result);
                                    context.Log.Info(msg);
                                    context.Fail(reason: msg);
                                }
                                else
                                {
                                    context.Log.Info("Successfully started transaction. TransactionId: {0}.", dto.TransactionId);
                                    context.Log.Info("Now sending transactional events...", dto.TransactionId);

                                    transactionId = dto.TransactionId;
                                    stage = Stage.Writing;
                                    for (int i = 0; i < eventsCnt; ++i)
                                    {
                                        var writeDto = new TcpClientMessageDto.TransactionWrite(
                                            transactionId,
                                            new[] 
                                            { 
                                                new TcpClientMessageDto.NewEvent(Guid.NewGuid().ToByteArray() ,
                                                                                 "TakeSomeSpaceEvent",
                                                                                 0,0,
                                                                                 Common.Utils.Helper.UTF8NoBom.GetBytes(Guid.NewGuid().ToString()),
                                                                                 Common.Utils.Helper.UTF8NoBom.GetBytes(Guid.NewGuid().ToString()))
                                            },
                                            false);
                                        var package = new TcpPackage(TcpCommand.TransactionWrite, Guid.NewGuid(), writeDto.Serialize());
                                        conn.EnqueueSend(package.AsByteArray());
                                    }
                                }

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

                                var dto = pkg.Data.Deserialize<TcpClientMessageDto.TransactionWriteCompleted>();
                                if (dto.Result != TcpClientMessageDto.OperationResult.Success)
                                {
                                    var msg = string.Format("Error while writing transactional event: {0} ({1}).", dto.Message, dto.Result);
                                    context.Log.Info(msg);
                                    context.Fail(reason: msg);
                                }
                                else
                                {
                                    writtenEvents += 1;
                                    if (writtenEvents == eventsCnt)
                                    {
//.........这里部分代码省略.........
开发者ID:jjvdangelo,项目名称:EventStore,代码行数:101,代码来源:TransactionWriteProcessor.cs

示例6: ReadFlood

        private void ReadFlood(CommandProcessorContext context, string eventStreamId, int clientsCnt, long requestsCnt)
        {
            context.IsAsync();

            var clients = new List<TcpTypedConnection<byte[]>>();
            var threads = new List<Thread>();
            var autoResetEvent = new AutoResetEvent(false);
            var sw2 = new Stopwatch();

            long all = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);

                int sent = 0;
                int received = 0;

                var client = context.Client.CreateTcpConnection(
                    context,
                    (conn, pkg) =>
                    {
                        Interlocked.Increment(ref received);

                        var localAll = Interlocked.Increment(ref all);
                        if (localAll % 1000 == 0) Console.Write(".");
                        if (localAll % 100000 == 0)
                        {
                            var elapsed = sw2.Elapsed;
                            sw2.Restart();
                            context.Log.Trace("\nDONE TOTAL {0} READS IN {1} ({2:0.0}/s).",
                                              localAll,
                                              elapsed,
                                              1000.0*100000/elapsed.TotalMilliseconds);
                        }
                        if (localAll == requestsCnt)
                            autoResetEvent.Set();
                    },
                    connectionClosed: (conn, err) =>
                    {
                        if (all < requestsCnt)
                            context.Fail(null, "Socket was closed, but not all requests were completed.");
                        else
                            context.Success();
                    });

                client.ConnectionClosed += (_, __) => context.Log.Debug("READS sent: {0}, received: {1}", sent, received);
                clients.Add(client);

                threads.Add(new Thread(() => 
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var read = new ClientMessageDto.ReadEvent(Guid.NewGuid(), eventStreamId, 0);
                        var package = new TcpPackage(TcpCommand.ReadEvent, read.Serialize());
                        client.EnqueueSend(package.AsByteArray());
                        
                        Interlocked.Increment(ref sent);
                        while (sent - received > context.Client.Options.ReadWindow)
                            Thread.Sleep(1);
                    }
                }));
            }

            var sw = Stopwatch.StartNew();
            sw2.Start();
            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }

            autoResetEvent.WaitOne();
            sw.Stop();

            foreach (var client in clients)
            {
                client.Close();
            }

            context.Log.Info("Completed. READS done: {0}.", all);

            var reqPerSec = (requestsCnt + 0.0)/sw.ElapsedMilliseconds*1000;
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             requestsCnt,
                             sw.ElapsedMilliseconds,
                             reqPerSec);

            PerfUtils.LogData(
                        Keyword,
                            PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                 PerfUtils.Col("requestsCnt", requestsCnt),
                                 PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                        PerfUtils.Row(PerfUtils.Col("readsCnt", all))
            );

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                        (int)reqPerSec);
         
            context.Success();
//.........这里部分代码省略.........
开发者ID:jpierson,项目名称:EventStore,代码行数:101,代码来源:ReadFloodProcessor.cs

示例7: Flood


//.........这里部分代码省略.........
                            elapsed = sw.Elapsed;

                        if (elapsed.TotalMinutes > runTimeMinutes)
                        {
                            done = true;
                            doneEvent.Set();
                            break;
                        }

                        if (sentCount == 0)
                        {
                            int elapsedMinutesInt = (int)elapsed.TotalMinutes;
                            lock (_randomLockRoot)
                            {
                                sentCount = minPerSecond == maxPerSecond 
                                            ? maxPerSecond : _random.Next(minPerSecond, maxPerSecond);
                                dataSizeCoefficient = _random.Next(8, 256);
                            }

                            if (currentMinute != elapsedMinutesInt)
                            {
                                currentMinute = elapsedMinutesInt;
                                context.Log.Info("\nElapsed {0} of {1} minutes, sent {2}; next block coef. {3}",
                                                 elapsedMinutesInt,
                                                 runTimeMinutes,
                                                 sent,
                                                 dataSizeCoefficient);
                            }

                            sleepTime = 1000 / sentCount;
                        }

                        var dataSize = dataSizeCoefficient * 8;
                        var write = new TcpClientMessageDto.WriteEvents(
                            esId,
                            ExpectedVersion.Any,
                            new[]
                            {
                                new TcpClientMessageDto.NewEvent(
                                    Guid.NewGuid().ToByteArray(),
                                    "TakeSomeSpaceEvent",
                                    0,0,
                                    Helper.UTF8NoBom.GetBytes("DATA" + dataSize.ToString(" 00000 ") + new string('*', dataSize)),
                                    Helper.UTF8NoBom.GetBytes("METADATA" + new string('$', 100)))
                            },
                            false);
                        var package = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), write.Serialize());
                        client.EnqueueSend(package.AsByteArray());

                        Interlocked.Increment(ref sent);

                        Thread.Sleep(sleepTime);
                        sentCount -= 1;

                        while (sent - received > context.Client.Options.WriteWindow/clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }));
            }

            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }

            doneEvent.WaitOne();
            sw.Stop();

            foreach (var client in clients)
            {
                client.Close();
            }

            context.Log.Info("Completed. Successes: {0}, failures: {1}", succ, fail);
            var reqPerSec = (requestsCnt + 0.0)/sw.ElapsedMilliseconds*1000;
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             requestsCnt,
                             sw.ElapsedMilliseconds,
                             reqPerSec);

            PerfUtils.LogData(
                    Keyword,
                    PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                         PerfUtils.Col("requestsCnt", requestsCnt),
                         PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                    PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail))
            );

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                        (int)reqPerSec);

            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt),
                100*fail/(fail + succ));

            context.Success();
        }
开发者ID:danieldeb,项目名称:EventStore,代码行数:101,代码来源:WriteLongTermProcessor.cs

示例8: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var fromNumber = 0;

            if (args.Length > 0)
            {
                if (args.Length > 2)
                    return false;

                eventStreamId = args[0];

                if (args.Length == 2)
                    fromNumber = int.Parse(args[1]);
            }

            context.IsAsync();

            var readDto = new ClientMessageDto.ReadEvent(Guid.NewGuid(), eventStreamId, fromNumber);
            var package = new TcpPackage(TcpCommand.ReadEvent, readDto.Serialize());

            var sw = new Stopwatch();

            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}]: Reading...", conn.EffectiveEndPoint);
                    sw.Start();
                    conn.EnqueueSend(package.AsByteArray());
                },
                handlePackage: (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.ReadEventCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    sw.Stop();

                    var dto = pkg.Data.Deserialize<ClientMessageDto.ReadEventCompleted>();

                    context.Log.Info("READ events from <{0}>:\n\n"
                                     + "\tCorrelationId: {1}\n"
                                     + "\tEventStreamId: {2}\n"
                                     + "\tEventNumber:   {3}\n"
                                     + "\tReadResult:    {4}\n"
                                     + "\tEventType:     {5}\n"
                                     + "\tData:          {6}\n"
                                     + "\tMetadata:      {7}\n",
                                     eventStreamId,
                                     dto.CorrelationId,
                                     dto.EventStreamId,
                                     dto.EventNumber,
                                     (SingleReadResult) dto.Result,
                                     dto.EventType,
                                     Encoding.UTF8.GetString(dto.Data ?? new byte[0]),
                                     Encoding.UTF8.GetString(dto.Metadata ?? new byte[0]));

                    context.Log.Info("Read request took: {0}.", sw.Elapsed);

                    PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)sw.ElapsedMilliseconds);

                    conn.Close();
                    context.Success();
                },
                connectionClosed: (connection, error) =>
                {
                    if (error == SocketError.Success)
                        context.Success();
                    else
                        context.Fail();
                });

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

示例9: PingFlood

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

            var doneEvent = new ManualResetEventSlim(false);
            var clients = new List<TcpTypedConnection<byte[]>>();
            var threads = new List<Thread>();
            long all = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                long received = 0;
                long sent = 0;
                var client = context.Client.CreateTcpConnection(
                    context,
                    (conn, msg) =>
                    {
                        Interlocked.Increment(ref received);
                        var pongs = Interlocked.Increment(ref all);
                        if (pongs % 10000 == 0) Console.Write('.');
                        if (pongs == requestsCnt)
                        {
                            context.Success();
                            doneEvent.Set();
                        }
                    },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), Payload);
                        client.EnqueueSend(package.AsByteArray());
                       
                        var localSent = Interlocked.Increment(ref sent);
                        while (localSent - Interlocked.Read(ref received) > context.Client.Options.PingWindow/clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }) { IsBackground = true });
            }

            var sw = Stopwatch.StartNew();
            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();
            clients.ForEach(client => client.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);

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

示例10: CreateTcpConnection

        public Connection CreateTcpConnection(CommandProcessorContext context, 
                                              Action<Connection, TcpPackage> handlePackage,
                                              Action<Connection> connectionEstablished = null,
                                              Action<Connection, SocketError> connectionClosed = null,
                                              bool failContextOnError = true,
                                              IPEndPoint tcpEndPoint = null)
        {
            var connectionCreatedEvent = new ManualResetEventSlim(false);
            Connection typedConnection = null;

            var connection = _connector.ConnectTo(
                Guid.NewGuid(),
                tcpEndPoint ?? TcpEndpoint,
                conn =>
                {
                    // we execute callback on ThreadPool because on FreeBSD it can be called synchronously
                    // causing deadlock
                    ThreadPool.QueueUserWorkItem(_ => 
                    {
                        if (!InteractiveMode)
                            Log.Info("Connected to [{0}, L{1}].", conn.RemoteEndPoint, conn.LocalEndPoint);
                        if (connectionEstablished != null)
                        {
                            if (!connectionCreatedEvent.Wait(10000))
                                throw new Exception("TcpTypedConnection creation took too long!");
                            connectionEstablished(typedConnection);
                        }
                    });
                },
                (conn, error) =>
                {
                    var message = string.Format("Connection to [{0}, L{1}] failed. Error: {2}.",
                                                conn.RemoteEndPoint, conn.LocalEndPoint, error);
                    Log.Error(message);

                    if (connectionClosed != null)
                        connectionClosed(null, error);

                    if (failContextOnError)
                        context.Fail(reason: string.Format("Socket connection failed with error {0}.", error));
                },
                verbose: !InteractiveMode);

            typedConnection = new Connection(connection, new RawMessageFormatter(_bufferManager), new LengthPrefixMessageFramer());
            typedConnection.ConnectionClosed +=
                (conn, error) =>
                {
                    if (!InteractiveMode || error != SocketError.Success)
                    {
                        Log.Info("Connection [{0}, L{1}] was closed {2}",
                                 conn.RemoteEndPoint, conn.LocalEndPoint,
                                 error == SocketError.Success ? "cleanly." : "with error: " + error + ".");
                    }

                    if (connectionClosed != null)
                        connectionClosed(conn, error);
                    else
                        Log.Info("connectionClosed callback was null");
                };
            connectionCreatedEvent.Set();

            typedConnection.ReceiveAsync(
                (conn, pkg) =>
                {
                    var package = new TcpPackage();
                    bool validPackage = false;
                    try
                    {
                        package = TcpPackage.FromArraySegment(new ArraySegment<byte>(pkg));
                        validPackage = true;

                        if (package.Command == TcpCommand.HeartbeatRequestCommand)
                        {
                            var resp = new TcpPackage(TcpCommand.HeartbeatResponseCommand, Guid.NewGuid(), null);
                            conn.EnqueueSend(resp.AsByteArray());
                            return;
                        }

                        handlePackage(conn, package);
                    }
                    catch (Exception ex)
                    {
                        Log.InfoException(ex,
                                          "[{0}, L{1}] ERROR for {2}. Connection will be closed.",
                                          conn.RemoteEndPoint, conn.LocalEndPoint,
                                          validPackage ? package.Command as object : "<invalid package>");
                        conn.Close(ex.Message);

                        if (failContextOnError)
                            context.Fail(ex);
                    }
                });

            return typedConnection;
        }
开发者ID:jjvdangelo,项目名称:EventStore,代码行数:95,代码来源:Client.cs

示例11: PingFloodWaiting

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

            var clients = new List<TcpTypedConnection<byte[]>>();
            var threads = new List<Thread>();
            var doneEvent = new AutoResetEvent(false);
            var clientsDone = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var autoResetEvent = new AutoResetEvent(false);
                var client = context.Client.CreateTcpConnection(
                    context,
                    (_, __) => autoResetEvent.Set(),
                    connectionClosed: (conn, err) =>
                    {
                        if (clientsDone < clientsCnt)
                            context.Fail(null, "Socket was closed, but not all requests were completed.");
                        else
                            context.Success();
                    });
                clients.Add(client);
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);

                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        //TODO GFY ping needs correlation id
                        var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
                        client.EnqueueSend(package.AsByteArray());

                        autoResetEvent.WaitOne();
                    }
                    if (Interlocked.Increment(ref clientsDone) == clientsCnt)
                        doneEvent.Set();
                }));
            }

            var sw = Stopwatch.StartNew();
            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }
            
            doneEvent.WaitOne();
            sw.Stop();

            clients.ForEach(x => x.Close());

            var reqPerSec = (requestsCnt + 0.0)/sw.ElapsedMilliseconds*1000;
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             requestsCnt,
                             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) (sw.ElapsedMilliseconds/requestsCnt));

            context.Success();
        }
开发者ID:vishal-h,项目名称:EventStore-1,代码行数:73,代码来源:PingFloodWaitingProcessor.cs

示例12: 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 corrid = Guid.NewGuid();
            var deleteDto = new ClientMessageDto.DeleteStream(eventStreamId, expectedVersion);
            var package = new TcpPackage(TcpCommand.DeleteStream, corrid, deleteDto.Serialize());

            var sw = new Stopwatch();
            var done = false;

            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}]: Trying to delete event stream '{1}'...", conn.EffectiveEndPoint, eventStreamId);
                    sw.Start();
                    conn.EnqueueSend(package.AsByteArray());
                },
                handlePackage: (conn, pkg) =>
                {
                    sw.Stop();

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

                    var dto = pkg.Data.Deserialize<ClientMessageDto.DeleteStreamCompleted>();

                    if (dto.ErrorCode == (int)OperationErrorCode.Success)
                        context.Log.Info("DELETED event stream {0}.", eventStreamId);
                    else
                        context.Log.Info("DELETION FAILED for event stream {0}: {1} ({2}).",
                                         eventStreamId,
                                         dto.Error,
                                         (OperationErrorCode) dto.ErrorCode);

                    context.Log.Info("Delete request took: {0}.", sw.Elapsed);

                    PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)sw.ElapsedMilliseconds);

                    done = true;

                    conn.Close();
                    context.Success();
                },
                connectionClosed:(connection, error) =>
                {
                    if (done && error == SocketError.Success)
                        context.Success();
                    else
                        context.Fail();
                });

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

示例13: WriteFlood


//.........这里部分代码省略.........
                            case TcpClientMessageDto.OperationResult.CommitTimeout:
                                Interlocked.Increment(ref commitTimeout);
                                break;
                            case TcpClientMessageDto.OperationResult.ForwardTimeout:
                                Interlocked.Increment(ref forwardTimeout);
                                break;
                            case TcpClientMessageDto.OperationResult.WrongExpectedVersion:
                                Interlocked.Increment(ref wrongExpVersion);
                                break;
                            case TcpClientMessageDto.OperationResult.StreamDeleted:
                                Interlocked.Increment(ref streamDeleted);
                                break;
                            default:
                                throw new ArgumentOutOfRangeException();
                        }
                        if (dto.Result != TcpClientMessageDto.OperationResult.Success)
                            if (Interlocked.Increment(ref fail)%1000 == 0)
                                Console.Write('#');
                        Interlocked.Increment(ref received);
                        var localAll = Interlocked.Increment(ref all);
                        if (localAll % 100000 == 0)
                        {
                            var elapsed = sw2.Elapsed;
                            sw2.Restart();
                            context.Log.Trace("\nDONE TOTAL {0} WRITES IN {1} ({2:0.0}/s) [S:{3}, F:{4} (WEV:{5}, P:{6}, C:{7}, F:{8}, D:{9})].",
                                              localAll, elapsed, 1000.0*100000/elapsed.TotalMilliseconds,
                                              succ, fail,
                                              wrongExpVersion, prepTimeout, commitTimeout, forwardTimeout, streamDeleted);
                        }
                        if (localAll == requestsCnt)
                        {
                            context.Success();
                            doneEvent.Set();
                        }
                    },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var corrid = Guid.NewGuid();
                        var write = new TcpClientMessageDto.WriteEvents(
                            streams[rnd.Next(streamsCnt)],
                            ExpectedVersion.Any,
                            new[]
                            {
                                new TcpClientMessageDto.NewEvent(Guid.NewGuid().ToByteArray(),
                                                                 "TakeSomeSpaceEvent",
                                                                 1,0,
                                                                 Common.Utils.Helper.UTF8NoBom.GetBytes("{ \"DATA\" : \"" + new string('*', size) + "\"}"),
                                                                 Common.Utils.Helper.UTF8NoBom.GetBytes("{ \"METADATA\" : \"" + new string('$', 100) + "\"}"))
                            },
                            false);
                        var package = new TcpPackage(TcpCommand.WriteEvents, corrid, write.Serialize());
                        _monitor.StartOperation(corrid);
                        client.EnqueueSend(package.AsByteArray());

                        var localSent = Interlocked.Increment(ref sent);
                        while (localSent - Interlocked.Read(ref received) > context.Client.Options.WriteWindow/clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }) { IsBackground = true });
            }

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

            context.Log.Info("Completed. Successes: {0}, failures: {1} (WRONG VERSION: {2}, P: {3}, C: {4}, F: {5}, D: {6})",
                             succ, fail,
                             wrongExpVersion, prepTimeout, commitTimeout, forwardTimeout, streamDeleted);

            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.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail)));

            var failuresRate = (int) (100 * fail / (fail + succ));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt), failuresRate);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-c{1}-r{2}-st{3}-s{4}-reqPerSec", Keyword, clientsCnt, requestsCnt, streamsCnt, size), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-c{1}-r{2}-st{3}-s{4}-failureSuccessRate", Keyword, clientsCnt, requestsCnt, streamsCnt, size), failuresRate);
            _monitor.GetMeasurementDetails();
            if (Interlocked.Read(ref succ) != requestsCnt)
                context.Fail(reason: "There were errors or not all requests completed.");
            else
                context.Success();
        }
开发者ID:adbrowne,项目名称:EventStore,代码行数:101,代码来源:WriteFloodProcessor.cs

示例14: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            string metadata = null;

            if (args.Length > 0)
            {
                if (args.Length > 2)
                    return false;
                eventStreamId = args[0];
                if (args.Length > 1)
                    metadata = args[1];
            }

            context.IsAsync();
            var createStreamDto = new TcpClientMessageDto.CreateStream(
                    eventStreamId,
                    Guid.NewGuid().ToByteArray(), 
                    Encoding.UTF8.GetBytes(metadata ?? string.Format("{{\"StreamName\": \"{0}\"}}", eventStreamId)),
                    true,
                    metadata == null);
            var package = new TcpPackage(TcpCommand.CreateStream, Guid.NewGuid(), createStreamDto.Serialize());

            var sw = new Stopwatch();

            context.Client.CreateTcpConnection(
                    context,
                    connectionEstablished: conn =>
                    {
                        context.Log.Info("[{0}]: Trying to create stream '{1}'...", conn.EffectiveEndPoint, eventStreamId);
                        sw.Start();
                        conn.EnqueueSend(package.AsByteArray());
                    },
                    handlePackage: (conn, pkg) =>
                    {
                        if (pkg.Command != TcpCommand.CreateStreamCompleted)
                        {
                            context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                            return;
                        }

                        sw.Stop();

                        var dto = pkg.Data.Deserialize<TcpClientMessageDto.CreateStreamCompleted>();
                        if (dto.Result == TcpClientMessageDto.OperationResult.Success)
                        {
                            context.Log.Info("Successfully created stream '{0}'.", eventStreamId);
                            PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)sw.ElapsedMilliseconds);
                        }
                        else
                        {
                            context.Log.Info("Error while creating stream {0}: {1} ({2}).", eventStreamId, dto.Message, dto.Result);
                        }

                        context.Log.Info("Create stream request took: {0}.", sw.Elapsed);
                        conn.Close();
                        context.Success();
                    },
                    connectionClosed: (connection, error) =>
                    {
                        if (error == SocketError.Success)
                            context.Success();
                        else
                            context.Fail();
                    });

            context.WaitForCompletion();
            return true;
        }
开发者ID:base31,项目名称:geteventstore_EventStore,代码行数:69,代码来源:CreateStreamProcessor.cs

示例15: PingFlood

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

            var autoResetEvent = new AutoResetEvent(false);
            var clients = new List<TcpTypedConnection<byte[]>>();
            var threads = new List<Thread>();
            var all = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                int sent = 0;
                int received = 0;

                var client = context.Client.CreateTcpConnection(
                    context,
                    (conn, msg) =>
                    {
                        Interlocked.Increment(ref received);
                        var pongs = Interlocked.Increment(ref all);
                        if (pongs % 10000 == 0)
                            Console.Write('.');
                        if (pongs == requestsCnt)
                            autoResetEvent.Set();
                    },
                    connectionClosed: (conn, err) =>
                    {
                        if (all < requestsCnt)
                            context.Fail(null, "Socket was closed, but not all requests were completed.");
                        else
                            context.Success();
                    });

                clients.Add(client);

                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var package = new TcpPackage(TcpCommand.Ping, Payload);
                        client.EnqueueSend(package.AsByteArray());
                        Interlocked.Increment(ref sent);

                        while (sent - received > context.Client.Options.PingWindow)
                            Thread.Sleep(1);
                    }
                }));
            }

            var sw = Stopwatch.StartNew();
            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }

            autoResetEvent.WaitOne();
            sw.Stop();

            foreach (var client in clients)
            {
                client.Close();
            }

            var reqPerSec = (requestsCnt + 0.0)/sw.ElapsedMilliseconds*1000;
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             requestsCnt,
                             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);

            context.Success();
        }
开发者ID:jpierson,项目名称:EventStore,代码行数:83,代码来源:PingFloodProcessor.cs


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