public async Task Connect(string url, string username, string password, List <SupportedProtocol> protocols, CancellationToken token) { try { var auth = Authorization.Basic(username, password); m_client = EtpFactory.CreateClient(WebSocketType.WebSocket4Net, url, "ShellSquare ETP Client", "1.4.1.1", SUBPROTOCOL, auth); var protocol1Info = protocols.Where(x => x.Protocol == 1).FirstOrDefault(); if (protocol1Info.Role.Equals("producer")) { m_client.Register <IChannelStreamingConsumer, ChannelStreamingConsumerHandler>(); m_client.Handler <IChannelStreamingConsumer>().OnChannelMetadata += HandleChannelMetadata; m_client.Handler <IChannelStreamingConsumer>().OnProtocolException += HandleProtocolException; m_client.Handler <IChannelStreamingConsumer>().OnChannelData += HandleChannelData; } else { m_client.Register <IChannelStreamingProducer, ChannelStreamingProducerHandler>(); } m_client.Register <IDiscoveryCustomer, DiscoveryCustomerHandler>(); m_client.Register <IStoreCustomer, StoreCustomerHandler>(); m_client.Handler <ICoreClient>().OnOpenSession += HandleOpenSession; await CreateSession(protocols); await m_client.OpenAsync(); } catch (Exception ex) { if (ex.InnerException != null) { throw new Exception($"{ex.Message} {ex.InnerException.Message}"); } throw; } }
/// <summary> /// Initializes common resources. /// </summary> /// <param name="container">The composition container.</param> protected void EtpSetUp(IContainer container) { _container = container; // Clean up any remaining resources _client?.Dispose(); _server?.Dispose(); // Get next available port number var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); // Update EtpServerUrl setting var uri = new Uri(TestSettings.EtpServerUrl); var url = TestSettings.EtpServerUrl.Replace($":{uri.Port}", $":{port}"); // Create server and client instances _server = CreateServer(port); _client = InitClient(CreateClient(url)); // Resolve dependencies early to avoid object disposed var streaming = container.Resolve <IChannelStreamingProducer>(); var discovery = container.Resolve <IDiscoveryStore>(); var store = container.Resolve <IStoreStore>(); // Register server handlers _server.Register(() => streaming); _server.Register(() => discovery); _server.Register(() => store); }
public async Task Connect(string url, string username, string password, CancellationToken token) { try { m_Time = DateTime.UtcNow; var protocols = new List <SupportedProtocol>(); SupportedProtocol p; p = EtpHelper.ToSupportedProtocol(Protocols.ChannelStreaming, "consumer"); protocols.Add(p); p = EtpHelper.ToSupportedProtocol(Protocols.Discovery, "store"); protocols.Add(p); var auth = Authorization.Basic(username, password); m_client = EtpFactory.CreateClient(WebSocketType.WebSocket4Net, url, m_ApplicationName, m_ApplicationVersion, SUBPROTOCOL, auth); m_client.Register <IChannelStreamingProducer, ChannelStreamingProducerHandler>(); m_client.Register <IDiscoveryCustomer, DiscoveryCustomerHandler>(); m_client.Register <IStoreCustomer, StoreCustomerHandler>(); m_client.Handler <ICoreClient>().OnOpenSession += HandleOpenSession; CreateSession(protocols); await m_client.OpenAsync(); } catch (Exception ex) { if (ex.InnerException != null) { throw new Exception($"{ex.Message} {ex.InnerException.Message}"); } throw; } }
private void HandleClient(IEtpClient client) { while (true) { Console.WriteLine("Select from the following options:"); Console.WriteLine(" R - Request Session"); Console.WriteLine(" C - Close Session"); if (client.EtpVersion == EtpVersion.v12) { Console.WriteLine(" P - Ping"); } foreach (var handler in Handlers) { handler.PrintConsoleOptions(); } Console.WriteLine(" Z - Clear"); Console.WriteLine(" X - Exit"); Console.WriteLine(); var info = Console.ReadKey(); Console.WriteLine(" - processing..."); Console.WriteLine(); if (IsKey(info, "R")) { client.Open(); } else if (IsKey(info, "C")) { client.CloseWebSocket("EtpClient closed."); } else if (IsKey(info, "P")) { if (client.EtpVersion == EtpVersion.v12) { client.Ping(); } } else if (IsKey(info, "Z")) { Console.Clear(); } else if (IsKey(info, "X")) { break; } else { foreach (var handler in Handlers) { if (handler.HandleConsoleInput(info)) { break; } } } } }
protected override void InitializeClient(IEtpClient client) { var clientStoreHandler = new CustomerHandler(); InitializeRegistrar(client, clientStoreHandler); clientStoreHandler.InitializeSession(client); Handlers.Add(clientStoreHandler); }
protected override void InitializeClient(IEtpClient client) { var clientHandler = new StoreHandler(TestDataStore); InitializeRegistrar(client, clientHandler); clientHandler.InitializeSession(client); Handlers.Add(clientHandler); }
public async Task SendChannelData(List <ChannelStreamingInfo> lstChannels) { //IDictionary<string, string> auth; //auth = Authorization.Basic(UserNameS, Password); //m_client = EtpFactory.CreateClient(WebSocketType.WebSocket4Net, URL, m_ApplicationName, m_ApplicationVersion, SUBPROTOCOL, auth); //m_client.Register<IChannelStreamingProducer, ChannelStreamingProducerHandler>(); var auth = Authorization.Basic(UserNameS, Password); m_client = EtpFactory.CreateClient(WebSocketType.WebSocket4Net, URL, m_ApplicationName, m_ApplicationVersion, SUBPROTOCOL, auth); m_client.Register <IChannelStreamingProducer, ChannelStreamingProducerHandler>(); while (true) { await SendChannelDataActual(lstChannels, m_client); await Task.Delay(TimeSpan.FromSeconds(10)); ////New Code ..Need to check is this required or not //var handler = m_client.Handler<IChannelStreamingProducer>(); ////index = index + 1; ////var timer = new System.Threading.Timer((e) => ////{ // await Task.Run(async () => // { // var receivedTime = DateTime.UtcNow; // var timediff = receivedTime - m_Time; // MessageHeader header = new MessageHeader(); // header.Protocol = (int)Protocols.ChannelStreaming; // header.MessageType = 3; // header.MessageId = EtpHelper.NextMessageId; // header.MessageFlags = 0; // header.CorrelationId = 0; // var recordData = Activator.CreateInstance<ChannelData>(); // recordData.Data = new List<DataItem>(); // Random random = new Random(); // foreach (var item in lstChannels) // { // TimeSpan t = (receivedTime - m_Epoch); // index = (long)t.TotalMilliseconds; // DataItem d = new DataItem(); // d.ChannelId = item.ChannelId; // d.Indexes = new List<long>(); // d.Indexes.Add(index); // d.Value = new DataValue(); // d.Value.Item = Math.Round(random.NextDouble() * 1000, 2);//random.Next(); // d.ValueAttributes = new List<DataAttribute>(); // recordData.Data.Add(d); // } // m_client.Handler<IChannelStreamingProducer>().ChannelData(header, recordData.Data); // string message = $"\nRequest: [Protocol {header.Protocol} MessageType {header.MessageType}]"; // Message?.Invoke(message + "\nChannel Data processed " + (receivedTime - m_Epoch).ToString(), 0, TraceLevel.Info); // }); // await Task.Delay(TimeSpan.FromSeconds(10)); ////}, null, startTimeSpan, periodTimeSpan); } }
/// <summary> /// Initializes the client. /// </summary> /// <param name="client">The ETP client.</param> /// <returns>The ETP client.</returns> protected IEtpClient InitClient(IEtpClient client) { // Register client handlers client.Register <IChannelStreamingConsumer, ChannelStreamingConsumerHandler>(); client.Register <IDiscoveryCustomer, DiscoveryCustomerHandler>(); client.Register <IStoreCustomer, StoreCustomerHandler>(); return(client); }
/// <summary> /// Disposes common resources. /// </summary> protected void EtpCleanUp() { _client?.Dispose(); _server?.Dispose(); _client = null; _server = null; TestSettings.Reset(); }
/// <summary> /// Opens a WebSocket connection and waits for the SocketOpened event to be called. /// </summary> /// <param name="client">The client.</param> /// <param name="milliseconds">The timeout, in milliseconds.</param> /// <returns>An awaitable task.</returns> public static async Task <bool> OpenAsyncWithTimeout(this IEtpClient client, int?milliseconds = null) { var onSessionOpened = HandleAsync <SessionOpenedEventArgs>(x => client.SessionOpened += x); var open = client.OpenAsync(); await Task.WhenAll(open, onSessionOpened).WaitAsync(milliseconds); return(client.IsWebSocketOpen); }
/// <summary> /// Initializes common resources. /// </summary> /// <param name="webSocketType">The WebSocket type.</param> /// <param name="etpSubProtocol">The ETP websocket sub-protocol</param> protected void SetUp(WebSocketType webSocketType, string etpSubProtocol) { // Clean up any remaining resources _client?.Dispose(); _server?.Dispose(); // Create server and client instances _server = CreateServer(webSocketType); _client = CreateClient(webSocketType, etpSubProtocol, _server.Uri.ToWebSocketUri().ToString()); }
/// <summary> /// Initializes common resources. /// </summary> /// <param name="webSocketType">The WebSocket type.</param> /// <param name="etpSubProtocol">The ETP websocket sub-protocol</param> protected void SetUpWithProxy(WebSocketType webSocketType, string etpSubProtocol) { // Clean up any remaining resources _client?.Dispose(); _server?.Dispose(); var proxiedServer = CreateServer(webSocketType); _server = new EtpSelfHostedProxyWebServer(GetAvailablePort(), proxiedServer); // Use hostname so .NET will connect through the proxy. var uri = new UriBuilder(proxiedServer.Uri.Scheme, "vcap.me", proxiedServer.Uri.Port, proxiedServer.Uri.AbsolutePath, proxiedServer.Uri.Query).Uri; _client = CreateClient(webSocketType, etpSubProtocol, uri.ToWebSocketUri().ToString()); }
/// <summary> /// Requests a new session and asserts. /// </summary> /// <param name="retries">The number of retries.</param> /// <returns>The <see cref="OpenSession" /> message args.</returns> protected async Task <ProtocolEventArgs <OpenSession> > RequestSessionAndAssert(int retries = 10) { try { var client = _client; // Register event handler for OpenSession response var onOpenSession = HandleAsync <OpenSession>( x => client.Handler <ICoreClient>().OnOpenSession += x); // Wait for Open connection var isOpen = await _client.OpenAsyncWithTimeout(); Assert.IsTrue(isOpen); // Wait for OpenSession var openArgs = await onOpenSession; // Verify OpenSession and Supported Protocols VerifySessionWithProtcols(openArgs, Protocols.ChannelStreaming, Protocols.Discovery, Protocols.Store); return(openArgs); } catch (TimeoutException) { if (retries < 1) { throw; } await Task.Delay(TestSettings.DefaultTimeoutInMilliseconds); Logger.Warn("Retrying connection attempt after timeout"); if (retries == 1) { _client?.Dispose(); _client = InitClient(CreateClient(TestSettings.FallbackServerUrl)); } else { EtpSetUp(_container); _server.Start(); } return(await RequestSessionAndAssert(retries - 1)); } }
/// <summary> /// Opens a WebSocket connection and waits for the SocketOpened event to be called. /// </summary> /// <param name="client">The client.</param> /// <param name="milliseconds">The timeout, in milliseconds.</param> /// <returns>An awaitable task.</returns> public static async Task <bool> OpenAsyncWithTimeout(this IEtpClient client, int?milliseconds = null) { await client.OpenAsync().WaitAsync(milliseconds); return(client.IsOpen); }
protected abstract void InitializeClient(IEtpClient client);
private async Task SendChannelDataActual(List <ChannelStreamingInfo> lstChannels, IEtpClient m_client) { var handler = m_client.Handler <IChannelStreamingProducer>(); // index = index + 1; await Task.Run(async() => { var receivedTime = DateTime.UtcNow; var timediff = receivedTime - m_Time; MessageHeader header = new MessageHeader(); header.Protocol = (int)Protocols.ChannelStreaming; header.MessageType = 3; header.MessageId = EtpHelper.NextMessageId; header.MessageFlags = 0; header.CorrelationId = 0; var recordData = Activator.CreateInstance <ChannelData>(); recordData.Data = new List <DataItem>(); Random random = new Random(); foreach (var item in lstChannels) { TimeSpan t = (receivedTime - m_Epoch); index = (long)t.TotalMilliseconds; DataItem d = new DataItem(); d.ChannelId = item.ChannelId; d.Indexes = new List <long>(); d.Indexes.Add(index); d.Value = new DataValue(); d.Value.Item = Math.Round(random.NextDouble() * 1000, 2);//random.Next(); d.ValueAttributes = new List <DataAttribute>(); recordData.Data.Add(d); } var a = m_client.Handler <IChannelStreamingProducer>().ChannelData(header, recordData.Data); string message = $"\nRequest: [Protocol {header.Protocol} MessageType {header.MessageType}]"; Message?.Invoke(message + "\nChannel Data processed " + (receivedTime - m_Epoch).ToString(), 0, TraceLevel.Info); }); }