private async Task Reconnect() { var reconnectingEvent = RaiseOnReconnecting(); var handshakeClient = _connectionFactory.CreateHandshakeClient(); var handshake = await handshakeClient.FirmShake(SlackKey); await _webSocketClient.Connect(handshake.WebSocketUrl); await Task.WhenAll(reconnectingEvent, RaiseOnReconnect()); }
public async Task EnsureConnectionOpen(string apiToken) { if (_webSocketClient.State != WebSocketClientState.Open) { _cts?.Cancel(); _cts = new CancellationTokenSource(30000); var uri = string.Format(BaseAddress, apiToken); await _webSocketClient.Connect(uri, CancellationToken.None).ConfigureAwait(false); _webSocketClient.MessageReceived += OnMessageReceived; } }
public void Connect(string host) { if (mConn != null && !mConn.state.IsDisconnected()) { DebugUtility.LogError(LoggerTags.Online, "Please disconnect this conn."); return; } DebugUtility.LogTrace(LoggerTags.Online, "Connnect to {0}", host); const string kSimProtocolStr = "sim://"; // sim : simulator if (host.StartsWith(kSimProtocolStr)) { string name = host.Substring(kSimProtocolStr.Length); var simulators = UnityEngine.Object.FindObjectsOfType <ScratchWebSocketClientSimulator>(); foreach (var simulator in simulators) { if (simulator.name.StartsWith(name, StringComparison.OrdinalIgnoreCase)) { mConn = simulator; } if (mConn != null) { break; } } if (mConn != null) { mConn.onConnected = OnConnected; mConn.onRecv = OnMessage; mConn.onError = OnError; mConn.onDisconnected = OnDisconnected; mConn.Connect(host); } else { mConn = NetworkFactory.CreateWebSocketSimulator <ScratchWebSocketClientSimulator>(host, true, OnConnected, OnDisconnected, OnMessage, OnError); } return; } if (host.StartsWith(WebBridgeClient.ProtocolHeader)) { mConn = NetworkFactory.CreateWebClient <WebBridgeClient>(host, true, OnConnected, OnDisconnected, OnMessage, OnError); return; } mConn = NetworkFactory.CreateWebClient(host, true, OnConnected, OnDisconnected, OnMessage, OnError); }
public override bool StartClient() { if (IsStarted) { throw new InvalidOperationException("Socket already started"); } var protocol = SecureConnection ? "wss" : "ws"; WebSocketClient = WebSocketClientFactory.Create($"{protocol}://{ConnectAddress}:{Port}/netcode"); WebSocketClient.Connect(); IsStarted = true; return(true); }
public override async void OnCreate() { base.OnCreate(); Log.Error("Service:", "WebSocketService STARTED"); try { if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { using Notification notification = new NotificationCompat.Builder(this, App.NonStopChannelIdForServices).SetContentTitle("Familia") .SetContentText("Ruleaza in fundal").SetSmallIcon(Resource.Drawable.logo).SetOngoing(true) .Build(); StartForeground(App.NonstopNotificationIdForServices, notification); } //RegisterReceiver(_charger, new IntentFilter(Intent.ActionHeadsetPlug)); bool ok = int.TryParse(Utils.GetDefaults("UserType"), out int type); Log.Error("ok", ok.ToString()); Log.Error("type", type.ToString()); if (ok) { if (type != 2) { await _socketClient.ConnectAsync(Constants.WebSocketAddress, Constants.WebSocketPort, this); } } _webSocketLocation.Connect(Constants.WebSocketLocationAddress, Constants.WebSocketPort, this); await Task.Run(async() => { try { string result = await GetData(); if (result == "{}") { throw new Exception("Error geting configuration from GIS"); } Utils.SetDefaults("IdPersoana", new JSONObject(result).GetInt("idPersoana").ToString()); } catch (Exception ex) { Log.Error("Configuration Error", ex.Message); } }); } catch (Exception e) { Console.WriteLine(e); //throw; } }
public override SocketTasks StartClient() { string conUrl = Url; if (conUrl.EndsWith("/")) { conUrl = conUrl.Substring(0, conUrl.Length - 1); } conUrl += "/mlapi-connection"; client = WebSocketClientFactory.Create(conUrl); client.SetOnOpen(() => { clientEventQueue.Enqueue(new ClientEvent() { Type = NetEventType.Connect, Payload = new ArraySegment <byte>() }); }); client.SetOnClose((code) => { clientEventQueue.Enqueue(new ClientEvent() { Type = NetEventType.Disconnect, Payload = new ArraySegment <byte>() }); }); client.SetOnPayload((payload) => { clientEventQueue.Enqueue(new ClientEvent() { Type = NetEventType.Disconnect, Payload = payload }); }); client.Connect(); return(SocketTask.Done.AsTasks()); }
/// <summary> /// Create webbridge instance /// </summary> /// <param name="url">e.g. "bridge://echo.websocket.org"</param> /// <param name="connectImmediatly">connect to host immediately or not</param> /// <param name="onConnected">the connected event</param> /// <param name="onDisconnected">the disconnected event</param> /// <param name="onRecv">on recv message event</param> /// <param name="onError">on error event</param> /// <returns>the interface of web-socket wrapper</returns> public static IWebSocketClient CreateWebClient <TWebClient>( string url, bool connectImmediatly, Action onConnected, Action <ENetCode> onDisconnected, Action <byte[]> onRecv, Action <string> onError) where TWebClient : IWebSocketClient { IWebSocketClient ws = Activator.CreateInstance <TWebClient>(); ws.onConnected = onConnected; ws.onRecv = onRecv; ws.onError = onError; ws.onDisconnected = onDisconnected; if (connectImmediatly) { ws.Connect(url); } return(ws); }
public int Connect(string node_url) { _wsc.Connect(node_url); _cancelletionTokenSource = new CancellationTokenSource(); _cancelletionToken = _cancelletionTokenSource.Token; _healthTask = new Task(() => { while (!_cancelletionToken.IsCancellationRequested) { if (_wsc.IsConnected()) { // build health request JObject request = JObject.FromObject( new { id = 0, jsonrpc = _jsonRpcParams.JsonrpcVersion, method = "system_health", @params = new JArray { } } ); _logger.Info("Health request"); _wsc.Send(request.ToString()); } for (var i = 0; i < Consts.HEALTH_REQUEST_TIME_SEC && !_cancelletionToken.IsCancellationRequested; i++) { Thread.Sleep(1000); } } }, _cancelletionToken, TaskCreationOptions.LongRunning); _healthTask.Start(); return(Consts.PAPI_OK); }
public int Connect(string node_url) { _wsc.Connect(node_url); return(Consts.PAPI_OK); }
private static async Task Reconnect(this IWebSocketClient webSocketClient, IRetryStrategy retryStrategy, CancellationToken cancellationToken = default) { await retryStrategy.Apply(async cancellationToken => await webSocketClient.Connect(cancellationToken), cancellationToken); }