示例#1
0
        static void SimulateSales(string country, string product)
        {
            using (GatewayWebSocketClient websocketClient = new GatewayWebSocketClient())
            {
                websocketClient.ConnectAsync("ws://localhost:31024/SalesServiceWS/").Wait();
                PostSalesModel postSalesModel = new PostSalesModel
                {
                    Product = product,
                    Country = country
                };

                IWsSerializer serializer = SerializerFactory.CreateSerializer();
                byte[]        payload    = serializer.SerializeAsync(postSalesModel).Result;

                WsRequestMessage mreq = new WsRequestMessage
                {
                    Operation = "sell",
                    Value     = payload
                };

                WsResponseMessage mresp = websocketClient.SendReceiveAsync(mreq, CancellationToken.None).Result;
                if (mresp.Result == WsResult.Error)
                {
                    Console.WriteLine("Error: {0}", Encoding.UTF8.GetString(mresp.Value));
                }
            }
        }
示例#2
0
        /// <summary>
        /// IWebSocketListener.ProcessWsMessageAsync
        /// </summary>
        public async Task <byte[]> ProcessWsMessageAsync(byte[] wsrequest, CancellationToken cancellationToken)
        {
            Logger.Debug(nameof(this.ProcessWsMessageAsync));

            ProtobufWsSerializer mserializer = new ProtobufWsSerializer();

            WsRequestMessage mrequest = await mserializer.DeserializeAsync <WsRequestMessage>(wsrequest);

            switch (mrequest.Operation)
            {
            case WSOperations.AddItem:
            {
                IWsSerializer    pserializer = SerializerFactory.CreateSerializer();
                PostProductModel payload     = await pserializer.DeserializeAsync <PostProductModel>(mrequest.Value);

                await this.PurchaseProduct(payload.ProductId, payload.Quantity);
            }
            break;
            }

            WsResponseMessage mresponse = new WsResponseMessage
            {
                Result = WsResult.Success
            };

            return(await mserializer.SerializeAsync(mresponse));
        }
示例#3
0
        public async Task <byte[]> ProcessWsMessageAsync(byte[] wsrequest, string session, CancellationToken cancellationToken)
        {
            Logger.Debug(nameof(this.ProcessWsMessageAsync));
            WsRequestMessage mrequest = await InitHelpers.GetMse().DeserializeAsync <WsRequestMessage>(wsrequest);

            WsResponseMessage mresponse = new WsResponseMessage();

            mresponse.Result = (int)WsResult.Success;
            if (dicRequest.ContainsKey((WSRequestMsgID)mrequest.MsgId))
            {
                Account  account = null;
                UserRole role    = null;
                Bag      bag     = null;
                var      info    = dicRequest[(WSRequestMsgID)mrequest.MsgId];
                if (info.ndAccount)
                {
                    account = await GetAccount(session);


                    //   account = await DataHelper.GetAccountBySessionAsync(this.StateManager, session);
                    if (account == null)
                    {
                        mresponse.Result = (int)WsResult.NotAccount;
                        return(await InitHelpers.GetMse().SerializeAsync(mresponse));
                    }
                }
                if (info.ndRole)
                {
                    role = await RoleDataHelper.Instance.GetRoleBySidAsync(session);

                    //role = await DataHelper.GetOnlineRoleBySessionAsync(this.StateManager, session);
                    if (role == null)
                    {
                        mresponse.Result = (int)WsResult.NotRole;
                        return(await InitHelpers.GetMse().SerializeAsync(mresponse));
                    }
                    bag = await BagDataHelper.Instance.GetBagByRoleId(role.Id);

                    if (bag == null)
                    {
                        bag = new Bag();
                    }
                }
                if (mresponse.Result == (int)WsResult.Success)
                {
                    SetRole(session, account, role, mrequest.Data, bag);
                    var ret = await info.handle();

                    mresponse.Result = (int)ret.Result;
                    mresponse.MsgId  = (int)info.send;
                    mresponse.Value  = await InitHelpers.GetMse().SerializeAsync(ret);
                }
            }
            else
            {
                mresponse.Result = (int)WsResult.NoneActionFunc;
            }
            return(await InitHelpers.GetMse().SerializeAsync(mresponse));
        }
示例#4
0
        public static async Task <byte[]> Make(WSResponseMsgID msgId, byte[] data)
        {
            WsResponseMessage result = new WsResponseMessage();

            result.MsgId  = (int)msgId;
            result.Result = 0;
            result.Value  = data;
            return(await InitHelpers.GetMse().SerializeAsync(result));
        }
示例#5
0
        /// <summary>
        /// IWebSocketListener.ProcessWsMessageAsync 消息分发过来进行处理
        /// </summary>
        public async Task <byte[]> ProcessWsMessageAsync(byte[] wsrequest, CancellationToken cancellationToken)
        {
            Logger.Debug(nameof(this.ProcessWsMessageAsync));

            ProtobufWsSerializer mserializer = new ProtobufWsSerializer();

            WsRequestMessage mrequest = await mserializer.DeserializeAsync <WsRequestMessage>(wsrequest);

            ///事件集中在这里处理  并且可以保存状态
            switch (mrequest.Operation)
            {
            case WSOperations.AddItem:
            {
                IWsSerializer    pserializer = SerializerFactory.CreateSerializer();
                PostProductModel payload     = await pserializer.DeserializeAsync <PostProductModel>(mrequest.Value); //取值

                await this.PurchaseProduct(payload.ProductId, payload.Quantity);                                      //数据处理
            }
            break;
            }

            PostProductModel m = new PostProductModel();

            m.ProductId = 100;
            m.Quantity  = 200;
            var m1 = await mserializer.SerializeAsync(m);

            //构造返回值
            WsResponseMessage mresponse = new WsResponseMessage
            {
                Result = WsResult.Success,
                Value  = m1
            };

            return(await mserializer.SerializeAsync(mresponse));
        }
示例#6
0
        public async Task <int> DoWorkAsyncWebSocket(int iterationsMax, int threadId, int threadCount, int maxProductsPerThread, int delayMs)
        {
            int iterations    = 0;
            int failedCounter = 0;

            try
            {
                Random rnd = new Random((threadId + 1) * DateTime.UtcNow.Millisecond);

                Stopwatch sw            = Stopwatch.StartNew();
                long      executionTime = sw.ElapsedMilliseconds;

                // Partition the Product Ids per thread
                int productListOffsetMin = (this.ProductIdsToPurchase.Count / threadCount) * threadId;
                int productListOffsetMax = (this.ProductIdsToPurchase.Count / threadCount) * (threadId + 1) - 1;
                // Use Max Products Per Thread?
                if (maxProductsPerThread > 0)
                {
                    maxProductsPerThread--;
                    if (productListOffsetMin + maxProductsPerThread < productListOffsetMax)
                    {
                        productListOffsetMax = productListOffsetMin + maxProductsPerThread;
                    }
                }
                //Console.WriteLine("{0} to {1} to {2}", threadId, productListOffsetMin, productListOffsetMax);

                int productId         = 0;
                int immediateQuantity = 0;

                // Websocket client to public gateway
                using (PublicGatewayWebSocketClient websocketClient = new PublicGatewayWebSocketClient())
                {
                    await websocketClient.ConnectAsync(ConnectionFactory.WebSocketServerName);

                    while (iterations < iterationsMax)
                    {
                        productId         = this.ProductIdsToPurchase[rnd.Next(productListOffsetMin, productListOffsetMax)];
                        immediateQuantity = rnd.Next(1, 4);

                        // Report status every X seconds
                        if ((sw.ElapsedMilliseconds - executionTime) > ReportStatusMs)
                        {
                            Console.WriteLine(OutputReport(threadId, immediateQuantity, productId, delayMs, failedCounter, iterations, sw.ElapsedMilliseconds));
                            executionTime = sw.ElapsedMilliseconds;
                        }

                        // Serialize PostDataModel
                        PostProductModel postProductModel = new PostProductModel
                        {
                            // generating new user id for every iteration
                            ProductId = productId,
                            Quantity  = immediateQuantity
                        };

                        IWsSerializer serializer = SerializerFactory.CreateSerializer();
                        byte[]        payload    = await serializer.SerializeAsync(postProductModel);

                        // Websocket send & receive message spec
                        WsRequestMessage mreq = new WsRequestMessage
                        {
                            PartitionKey = productId,
                            Operation    = WSOperations.AddItem,
                            Value        = payload
                        };

                        WsResponseMessage mresp = await websocketClient.SendReceiveAsync(mreq, CancellationToken.None);

                        if (mresp.Result == WsResult.Error)
                        {
                            Console.WriteLine("Error: {0}", Encoding.UTF8.GetString(mresp.Value));
                        }

                        if (mresp.Result != WsResult.Success)
                        {
                            failedCounter++;
                        }

                        iterations++;

                        if (delayMs > -1 && iterations < iterationsMax)
                        {
                            await Task.Delay(delayMs);
                        }
                    }
                    Console.WriteLine(
                        "Completed: " + OutputReport(threadId, immediateQuantity, productId, delayMs, failedCounter, iterations - 1, sw.ElapsedMilliseconds));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return(iterations);
        }