Пример #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
        /// <summary>
        /// 传入客户端数据
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        public async void OnDataReceivedAsync(WebSocketSession session, byte[] value)
        {
            //收到数据处理
            //对数据 value 进行 protobuf解包处理 验证sign  对于sign不正确的 直接返回  保留正确的包继续逻辑
            WsRequestMessage mrequest = InitHelpers.GetMse().DeserializeAsync <WsRequestMessage>(value).Result;

            //if (!mrequest.SignKey.Equals(CheckSign(sign)))
            //{
            //TODO 验证处理
            // return  null;
            //}
            byte[] wsresponse = null;
            try
            {
                // dispatch to App provided function with requested
                //  wsresponse = handler.ProcessWsMessageAsync(value, session.SessionID, cancellationToken).Result;
                wsresponse = _msgQueue.ProcessWsMessageAsync(value, session.SessionID, cancellationToken).Result;
            }
            catch (Exception ex)
            {
                // catch any error in the appAction and notify the client
                wsresponse = new ProtobufWsSerializer().SerializeAsync(
                    new WsResponseMessage
                {
                    MsgId  = 0,
                    Result = (int)WsResult.Error,
                    Value  = Encoding.UTF8.GetBytes(ex.Message)
                }).Result;
            }
            session.Send(wsresponse, 0, wsresponse.Length);
            //TODO: 收到二进制数据处理
        }
Пример #4
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));
        }
        /// <summary>
        /// Re-uses the open websocket connection (assumes one is already created/connected)
        /// </summary>
        public async Task <WsResponseMessage> SendReceiveAsync(WsRequestMessage msgspec, CancellationToken cancellationToken)
        {
            if (this.websocketManager == null)
            {
                throw new ApplicationException("SendReceiveAsync requires an open websocket client");
            }

            // Serialize Msg payload
            IWsSerializer mserializer = new ProtobufWsSerializer();

            byte[] request = await mserializer.SerializeAsync(msgspec);

            byte[] response = await this.websocketManager.SendReceiveAsync(request);

            return(await mserializer.DeserializeAsync <WsResponseMessage>(response));
        }
        public async Task <byte[]> ProcessWsMessageAsync(
            byte[] wsrequest, CancellationToken cancellationToken
            )
        {
            IWsSerializer    mserializer = new ProtobufWsSerializer();
            WsRequestMessage mrequest    = await mserializer.DeserializeAsync <WsRequestMessage>(wsrequest);

            ServicePartitionClient <WsCommunicationClient> serviceClient =
                new ServicePartitionClient <WsCommunicationClient>(
                    this.clientFactory,
                    ConnectionFactory.StockServiceUri,
                    partitionKey: new ServicePartitionKey(mrequest.PartitionKey),       //根据消息分发
                    listenerName: ServiceConst.ListenerWebsocket);

            return(await serviceClient.InvokeWithRetryAsync(async client => await client.SendReceiveAsync(wsrequest), cancellationToken));
        }
Пример #7
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));
        }
Пример #8
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);
        }