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)); } } }
/// <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)); }
private ISerializer GetSerializer() { return(SingletonLocker.Lock(ref _serializerFactory, this, () => { return new Func <ISerializer>(() => { ISerializer _serializer = null; if (Setting.SerializerType != null) { _serializer = Setting.SerializerType.New <ISerializer>(); } if (_serializer == null) { _serializer = ServiceProvider.TryGetService(() => SerializerFactory.CreateSerializer()); } if (_serializer == null) { var option = new JsonSerializeOption(); option.Converters.Add(new FullDateTimeJsonConverter()); _serializer = new JsonSerializer(option); } return _serializer; }); })()); }
public void CanCommunicate() { var plane = TestGeometry.CreateUnitPlane("Plane"); var serializerFactory = new SerializerFactory(); var serializer = serializerFactory.CreateSerializer(); var communicatorFactory = new CommunicatorFactory(); var primaryCommunicator = communicatorFactory.CreatePrimaryCommunicator(serializer); primaryCommunicator.Connect(); var secondaryCommunicator = communicatorFactory.CreateSecondaryCommunicator(serializer); secondaryCommunicator.Connect(); Task.Delay(500).Wait(); primaryCommunicator.Send(plane); Task.Delay(500).Wait(); Assert.True(secondaryCommunicator.HasReceivedTransactions); var transaction = secondaryCommunicator.Receive(); var deserializedPlane = serializer.Deserialize<VisualizerMesh>(transaction.Payload); Assert.Equal(plane.Label, deserializedPlane.Label); secondaryCommunicator.Disconnect(); primaryCommunicator.Disconnect(); Assert.False(primaryCommunicator.IsConnected); Assert.False(secondaryCommunicator.IsConnected); }
public static IWsSerializer GetPse() { if (pserializer != null) { return(pserializer); } else { return(pserializer = SerializerFactory.CreateSerializer()); } }
public void CanSerializeAndDeserializeString() { var name = "Plane"; var factory = new SerializerFactory(); var serializer = factory.CreateSerializer(); var stream = serializer.SerializeToStream(name); var deserializedName = serializer.Deserialize <string>(stream); Assert.Equal(name, deserializedName); }
void Start() { var factory = new UnityFactory(); scene = factory.CreateScene(); var serializerFactory = new SerializerFactory(); var serializer = serializerFactory.CreateSerializer(); var communicatorFactory = new CommunicatorFactory(); communicator = communicatorFactory.CreatePrimaryCommunicator(serializer); visualizer = factory.CreateVisualizer(scene, serializer, communicator); }
internal static void Bind(IServiceCollection services, IConfiguration configuration) { ConfigurationUnity.Bind <LoggingConfigurationSection>(configuration); ConfigurationUnity.Bind <CachingConfigurationSection>(configuration); ConfigurationUnity.Bind <ContainerConfigurationSection>(configuration); ConfigurationUnity.Bind <SubscribeConfigurationSection>(configuration); if (services != null) { services.AddSingleton(typeof(ILogger), s => LoggerFactory.CreateLogger()); services.AddSingleton(typeof(ICacheManager), s => CacheManagerFactory.CreateManager()); services.AddSingleton(typeof(ISubscribeManager), s => SubscribeManagerFactory.CreateManager()); services.AddSingleton(typeof(ITextSerializer), s => SerializerFactory.CreateSerializer()); } }
public void SecondaryWithoutPrimaryTimesOut() { var serializerFactory = new SerializerFactory(); var serializer = serializerFactory.CreateSerializer(); var communicatorFactory = new CommunicatorFactory(); var secondaryCommunicator = communicatorFactory.CreateSecondaryCommunicator(serializer); secondaryCommunicator.Connect(); Task.Delay(Constants.ConnectionTimeout + 1000).Wait(); Assert.False(secondaryCommunicator.IsConnected); secondaryCommunicator.Disconnect(); }
public void CanSerializeAndDeserializeMesh() { var plane = TestGeometry.CreateUnitPlane("Plane"); var factory = new SerializerFactory(); var serializer = factory.CreateSerializer(); var transaction = new Transaction(typeof(VisualizerMesh), serializer.SerializeToStream(plane)); var stream = serializer.SerializeToStream(transaction); var deserializedTransaction = serializer.Deserialize <Transaction>(stream); Assert.Equal(typeof(VisualizerMesh).Name, transaction.PayloadType); var deserializedPlane = serializer.Deserialize <VisualizerMesh>(deserializedTransaction.Payload); Assert.Equal(plane.Label, deserializedPlane.Label); }
public VisualizerProcess CreateVisualizerProcess(VisualizerType visualizerType) { var serializerFactory = new SerializerFactory(); var serializer = serializerFactory.CreateSerializer(); var communicatorFactory = new CommunicatorFactory(); var communicator = communicatorFactory.CreateSecondaryCommunicator(serializer); switch (visualizerType) { case VisualizerType.Unity: return(new UnityVisualizerProcess(communicator)); case VisualizerType.UnityEditor: return(new UnityEditorVisualizerProcess(communicator)); default: return(null); } }
public void SerializeLevel() { #if NETFX_CORE throw new System.NotImplementedException("Level prefab saving not implemented in Windows 8 yet."); #else using (StreamWriter streamWriter = new StreamWriter(filepath)) { ISerializer <LevelPrefab> serializer = SerializerFactory.CreateSerializer <LevelPrefab>(); serializer.WriteObject(this, streamWriter.BaseStream); } #if DEBUG using (StreamWriter streamWriter = new StreamWriter(@"..\..\..\" + filepath)) { ISerializer <LevelPrefab> serializer = SerializerFactory.CreateSerializer <LevelPrefab>(); serializer.WriteObject(this, streamWriter.BaseStream); } #endif #endif }
public LevelPrefab GetLevelPrefab(string filepath) { try { LevelPrefab level; using (Stream stream = TitleContainer.OpenStream(filepath)) { ISerializer <LevelPrefab> serializer = SerializerFactory.CreateSerializer <LevelPrefab>(); level = serializer.ReadObject(stream); } return(level); } catch (FileNotFoundException) { return(new LevelPrefab { filepath = filepath }); } }
public void SecondaryTriesRepeatedlyToConnect() { var serializerFactory = new SerializerFactory(); var serializer = serializerFactory.CreateSerializer(); var communicatorFactory = new CommunicatorFactory(); var primaryCommunicator = communicatorFactory.CreatePrimaryCommunicator(serializer); var secondaryCommunicator = communicatorFactory.CreateSecondaryCommunicator(serializer); secondaryCommunicator.Connect(); Task.Delay(Constants.ConnectionTimeout * 3).Wait(); Assert.False(secondaryCommunicator.IsConnected); primaryCommunicator.Connect(); Task.Delay(Constants.ConnectionTimeout * 2).Wait(); Assert.True(secondaryCommunicator.IsConnected); secondaryCommunicator.Disconnect(); primaryCommunicator.Disconnect(); }
public void CanSendMultipleMessages() { var serializerFactory = new SerializerFactory(); var serializer = serializerFactory.CreateSerializer(); var communicatorFactory = new CommunicatorFactory(); var primaryCommunicator = communicatorFactory.CreatePrimaryCommunicator(serializer); primaryCommunicator.Connect(); var secondaryCommunicator = communicatorFactory.CreateSecondaryCommunicator(serializer); secondaryCommunicator.Connect(); Task.Delay(500).Wait(); for (var i = 0; i < 5; i++) { var geometryName = "Plane" + i; var plane = TestGeometry.CreateUnitPlane(geometryName); primaryCommunicator.Send(plane); Task.Delay(500).Wait(); var transactionFromPrimary = secondaryCommunicator.Receive(); var deserializedPlaneFromPrimary = serializer.Deserialize<VisualizerMesh>(transactionFromPrimary.Payload); secondaryCommunicator.Send(deserializedPlaneFromPrimary); Task.Delay(500).Wait(); var transactionFromSecondary = primaryCommunicator.Receive(); var deserializedPlaneFromSecondary = serializer.Deserialize<VisualizerMesh>(transactionFromSecondary.Payload); Assert.Equal(deserializedPlaneFromPrimary.Label, deserializedPlaneFromSecondary.Label); } secondaryCommunicator.Disconnect(); primaryCommunicator.Disconnect(); }
/// <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)); }
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); }
protected virtual ITextSerializer CreateSerializer() { return(SerializerFactory.CreateSerializer() as ITextSerializer ?? new JsonSerializer()); }