public void Init(string ip, bool isBlazor = false) { hubConnection = new HubConnectionBuilder() .WithUrl($"http://{ip}:5000/hubs/chat") .Build(); hubConnection.Closed += async(error) => { OnConnectionClosed?.Invoke(this, new MessageEventArgs("Connection closed...")); IsConnected = false; await Task.Delay(random.Next(0, 5) * 1000); try { await ConnectAsync(); } catch (Exception ex) { // Exception! } }; hubConnection.On <string, string>("ReceiveMessage", (user, message) => { var finalMessage = $"{user} says {message}"; OnReceivedMessage?.Invoke(this, new MessageEventArgs(finalMessage)); }); hubConnection.On <string>("EnteredOrLeft", (message) => { OnEnteredOrExited?.Invoke(this, new MessageEventArgs(message)); }); }
/// <summary> /// Constructor with standard settings for a new HarmonyClient /// </summary> /// <param name="host">IP or hostname</param> /// <param name="token">Auth-token, or guest</param> /// <param name="port">The port to connect to, default 5222</param> /// <param name="keepAliveInterval">an optional keep alive interval, default is 50, Harmony needs 60 seconds</param> private HarmonyClient(string host, string token, int port = 5222, int?keepAliveInterval = 50) { Token = token; _xmpp = new XmppClientConnection(host, port) { UseStartTLS = false, UseSSL = false, UseCompression = false, AutoResolveConnectServer = false, AutoAgents = false, AutoPresence = true, AutoRoster = true, // For https://github.com/Lakritzator/harmony/issues/19 KeepAliveInterval = keepAliveInterval ?? 120, // 120 is the underlying default KeepAlive = keepAliveInterval.HasValue }; // Configure Sasl not to use auto and PLAIN for authentication _xmpp.OnSaslStart += SaslStartHandler; _xmpp.OnLogin += OnLoginHandler; _xmpp.OnIq += OnIqResponseHandler; _xmpp.OnMessage += OnMessage; _xmpp.OnSocketError += ErrorHandler; // Inform anyone who it may concern _xmpp.OnClose += sender => OnConnectionClosed?.Invoke(this, EventArgs.Empty); // Open the connection, do the login _xmpp.Open($"{token}@x.com", token); }
protected void SendConnectionClosed(TCPServer TCPServer, DateTime ServerTimestamp, IPSocket RemoteSocket, String ConnectionId, ConnectionClosedBy ClosedBy) { OnConnectionClosed?.Invoke(TCPServer, ServerTimestamp, RemoteSocket, ConnectionId, ClosedBy); }
public void DoClose() { Close(); Dispose(); OnConnectionClosed?.Invoke(this, new ConnectionInfo { Num = _id, Description = string.Empty, Time = DateTime.Now }); }
private void _hwsClient_Closed(object sender, EventArgs e) { OnConnectionClosed?.Invoke(this, this.SubItemName); if (NeedAutoReconnect) { InitWSClient(); } }
private void _webSocket_OnMessage(object sender, string message) { if (_encrypted) { var encrypted = DecryptMessage(message); var baseMessage = JsonConvert.DeserializeObject <LoxoneApiResponse <LoxoneApiResponseLL> >(encrypted); if (baseMessage.Data.Code == 200) { if (_connectionState == ConnectionState.AcquireToken) { var data = JsonConvert.DeserializeObject <LoxoneApiResponse <GetKeyResponseLL> >(encrypted); var pwHash = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes($"{password}:{data.Data.Value.Salt}")).ToHex(true); var hash = $"{Username}:{pwHash}".CalculateHmacSha1(Automatica.Core.Driver.Utility.Utils.StringToByteArray(data.Data.Value.Key)); var cmd = $"salt/{GenerateSalt()}/jdev/sys/gettoken/{hash}/{Username}/4/{LoxoneUuid}/AutomaticaCoreServer"; var msg = EncryptMessageForMs(cmd); _connectionState = ConnectionState.SaveToken; _webSocket.Send(msg); } else if (_connectionState == ConnectionState.SaveToken) { var data = JsonConvert.DeserializeObject <LoxoneApiResponse <TokenResponseLL> >(encrypted); _connectionState = ConnectionState.SendEnableUpdates; _encrypted = false; _webSocket.Send(EncryptMessageForMs($"salt/{GenerateSalt()}/jdev/sps/enablebinstatusupdate", false)); } } else { //TODO: specify why OnConnectionClosed?.Invoke(this, System.EventArgs.Empty); } } else { var baseMessage = JsonConvert.DeserializeObject <LoxoneApiResponse <LoxoneApiResponseLL> >(message); if (baseMessage.Data.Code == 200) { _encrypted = true; if (_connectionState == ConnectionState.ExchangeKeys) { var data = JsonConvert.DeserializeObject <LoxoneApiResponse <EncryptedMessageResponse> >(message); var decryptedMessage = DecryptMessage(data.Data.Value); _connectionState = ConnectionState.AcquireToken; AcquireToken(); } else if (_connectionState == ConnectionState.SendEnableUpdates) { //do nothing } } } }
public void Init(string url, bool useHttps) { var port = string.Empty; // ios || android if (url.Equals("localhost") || url.Equals("10.0.2.2")) { port = useHttps ? ":5001" : ":5000"; } string completeUrl = string.Format("http{0}://{1}{2}/hubs/chat", useHttps ? "s" : string.Empty, url, port); hubConnection = new HubConnectionBuilder().WithUrl(completeUrl).Build(); // Closing connection hubConnection.Closed += async(error) => { OnConnectionClosed?.Invoke(this, new MessageEventArgs("", "Closing connection")); connected = false; // Reconnect await Task.Delay(3000); try { await ConnectAsync(); } catch (Exception e) { Debug.WriteLine(e); } }; // Joining/leaving a group hubConnection.On <string>("EnterOrLeave", (message) => { OnEnterOrLeave?.Invoke(this, new MessageEventArgs(message, message)); }); hubConnection.On <string>("Enter", (user) => { OnEnterOrLeave?.Invoke(this, new MessageEventArgs(user, $"{user} joined")); }); hubConnection.On <string>("Leave", (user) => { OnEnterOrLeave?.Invoke(this, new MessageEventArgs(user, $"{user} left")); }); // Receive message hubConnection.On <string, string>("ReceiveMessage", (user, message) => { OnReceiveMessage?.Invoke(this, new MessageEventArgs(user, message)); }); }
public void Init(string urlRoot, bool useHttps) { random = new Random(); var port = (urlRoot == "localhost" || urlRoot == "10.0.2.2") ? (useHttps ? ":5001" : ":5000") : string.Empty; var url = $"http{(useHttps ? "s" : string.Empty)}://{urlRoot}{port}/hubs/chat"; hubConnection = new HubConnectionBuilder() .WithUrl(url) .WithAutomaticReconnect() .Build(); hubConnection.Closed += async(error) => { OnConnectionClosed?.Invoke(this, new MessageEventArgs("Connection closed...", string.Empty)); IsConnected = false; await Task.Delay(random.Next(0, 5) * 1000); try { await ConnectAsync(); } catch (Exception ex) { // Exception! Debug.WriteLine(ex); } }; hubConnection.On <string, string>("ReceiveMessage", (user, message) => { OnReceivedMessage?.Invoke(this, new MessageEventArgs(message, user)); }); hubConnection.On <string>("Entered", (user) => { OnEnteredOrExited?.Invoke(this, new MessageEventArgs($"{user} entered.", user)); }); hubConnection.On <string>("Left", (user) => { OnEnteredOrExited?.Invoke(this, new MessageEventArgs($"{user} left.", user)); }); hubConnection.On <string>("EnteredOrLeft", (message) => { OnEnteredOrExited?.Invoke(this, new MessageEventArgs(message, message)); }); }
protected internal void SendConnectionClosed(DateTime ServerTimestamp, IPSocket RemoteSocket, String ConnectionId, ConnectionClosedBy ClosedBy) { OnConnectionClosed?.Invoke(this, ServerTimestamp, RemoteSocket, ConnectionId, ClosedBy); }
void ConnectionClosed(Response response) { Unity.Console.DebugLog("ApiManager class", Unity.Console.SetMagentaColor("Regular Callback:"), "ConnectionClosed()"); ResetApi(); response.SendResultData <string>(reason => { if (OnConnectionClosed != null) { OnConnectionClosed.Invoke(reason); } }); }
public void Init() { IsConnected = false; random = new Random(); ListaKonekcija = new ObservableCollection <string>(); string username = BaseAPIService.Username; string password = BaseAPIService.Password; string kredencijali = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password)); hubKonekcija = new HubConnectionBuilder() .WithUrl(hubUrl, opcije => opcije.Headers.Add("Authorization", "Basic " + kredencijali)) .Build(); hubKonekcija.Closed += async(error) => { OnConnectionClosed?.Invoke(this, new MessageEventArgs("Disconnected..")); IsConnected = false; await Task.Delay(random.Next(0, 5) * 1000); try { await ConnectAsync(); } catch (Exception) { // Exception! } }; hubKonekcija.On <List <string> >("GetKonekcije", (_listaKonekcija) => { Device.BeginInvokeOnMainThread(() => { ListaKonekcija.Clear(); foreach (var i in _listaKonekcija) { ListaKonekcija.Add(i); } }); }); hubKonekcija.On <string, string, int>("PrimiNotifikacije", (tim1, tim2, id) => { var notifikacija = "Evidentirana je utakmica izmedju " + tim1 + " i " + tim2; primiNotifikacije?.Invoke(this, new MessageEventArgs(notifikacija)); }); hubKonekcija.On <List <string>, string, string, int>("startaj", (List <string> favoriti, string tim1, string tim2, int id) => { _ = PosaljiNotifikacijeAsync(favoriti, tim1, tim2, id); }); }
public void Stop() { lock (_socketLocker) { _stopping = true; LazyAsync.Invoke(() => { if (OnConnectionClosed != null) { OnConnectionClosed.Invoke(this); } Dispose(); }); } }
public void Start() { processorTask = Task.Run(() => { stream = connection.GetStream(); while (!stop && connection.Connected) { if (stream.DataAvailable) { ServiceRequests(); } Thread.Sleep(500); } OnConnectionClosed?.Invoke(this, null); }); }
public void Init(string urlRoot, bool useHttps) { random = new Random(); var url = $"http{(useHttps ? "s" : string.Empty)}://{urlRoot}/hubs/chat"; hubConnection = new HubConnectionBuilder() #if BLAZOR .WithUrl(url, opt => { opt.LogLevel = SignalRLogLevel.Trace; // Client log level opt.SkipNegotiation = true; opt.Transport = HttpTransportType.WebSockets; // Which transport you want to use for this connection }) #else .WithUrl(url) #endif .Build(); #if BLAZOR hubConnection.OnClose(async(error) => #else hubConnection.Closed += async(error) => #endif { OnConnectionClosed?.Invoke(this, new MessageEventArgs("Connection closed...")); IsConnected = false; await Task.Delay(random.Next(0, 5) * 1000); try { await ConnectAsync(); } catch (Exception ex) { // Exception! Debug.WriteLine(ex); } #if BLAZOR }); #else };
private void ThreadMain() { long num = m_threadExecutionUid = DateTime.Now.Ticks; Log.Info(string.Format("Starting {0} receive thread (id {1})", "TcpConnectionLayer", num), 88, "C:\\BuildAgents\\AgentB\\work\\cub_client_win64_develop\\client\\DofusCube.Unity\\Assets\\Core\\Code\\Network\\Spin2\\Layers\\TcpConnectionLayer.cs"); byte[] array = new byte[8192]; try { while (m_networkStream != null && m_threadExecutionUid == num) { int num2 = m_networkStream.Read(array, 0, 8192); if (num2 <= 0) { break; } byte[] array2 = new byte[num2]; Buffer.BlockCopy(array, 0, array2, 0, num2); OnData(array2); } } catch (IOException arg) { if (m_threadExecutionUid == num) { Log.Info($"IOException on socket: {arg}", 119, "C:\\BuildAgents\\AgentB\\work\\cub_client_win64_develop\\client\\DofusCube.Unity\\Assets\\Core\\Code\\Network\\Spin2\\Layers\\TcpConnectionLayer.cs"); } } catch (Exception arg2) { if (m_threadExecutionUid == num) { Log.Error(string.Format("Unexpected Exception in {0}: {1}", "TcpConnectionLayer", arg2), 128, "C:\\BuildAgents\\AgentB\\work\\cub_client_win64_develop\\client\\DofusCube.Unity\\Assets\\Core\\Code\\Network\\Spin2\\Layers\\TcpConnectionLayer.cs"); } } finally { Log.Info(string.Format("Exiting {0} receive thread (id {1})", "TcpConnectionLayer", num), 134, "C:\\BuildAgents\\AgentB\\work\\cub_client_win64_develop\\client\\DofusCube.Unity\\Assets\\Core\\Code\\Network\\Spin2\\Layers\\TcpConnectionLayer.cs"); OnConnectionClosed?.Invoke(); } }
public NetServer(IPEndPoint endpoint, int maxConnections) { this.Endpoint = endpoint; this.server = new NetManager(listener, maxConnections, "Phinix") { PingInterval = 5000, DisconnectTimeout = 30000 }; this.connectedPeers = new Dictionary <string, NetPeer>(); // Subscribe to events listener.PeerConnectedEvent += (peer) => { // Add or update the peer's connection string connectionId = peer.ConnectId.ToString("X"); if (connectedPeers.ContainsKey(connectionId)) { connectedPeers[connectionId] = peer; } else { connectedPeers.Add(connectionId, peer); } // Raise the connection established event for this peer OnConnectionEstablished?.Invoke(this, new ConnectionEventArgs(connectionId)); }; listener.PeerDisconnectedEvent += (peer, info) => { // Remove the peer's connection string connectionId = peer.ConnectId.ToString("X"); connectedPeers.Remove(connectionId); // Raise the connection established event for this peer OnConnectionClosed?.Invoke(this, new ConnectionEventArgs(connectionId)); }; }
public void Init() { IsConnected = false; random = new Random(); ListaKonekcija = new ObservableCollection <string>(); string username = BaseAPIService.Username; string password = BaseAPIService.Password; string kredencijali = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password)); hubKonekcija = new HubConnectionBuilder() .WithUrl(hubUrl, opcije => opcije.Headers.Add("Authorization", "Basic " + kredencijali)) .Build(); hubKonekcija.Closed += async(error) => { OnConnectionClosed?.Invoke(this, new MessageEventArgs("Disconnected..")); IsConnected = false; }; hubKonekcija.On <List <string> >("GetKonekcije", (_listaKonekcija) => { Device.BeginInvokeOnMainThread(() => { ListaKonekcija.Clear(); foreach (var i in _listaKonekcija) { ListaKonekcija.Add(i); } }); }); hubKonekcija.On <string, string, string, string>("PrimiPoruku", (poruka, posiljatelj, primatelj, vrijeme) => { ChatPoruka nova = new ChatPoruka(poruka, posiljatelj, primatelj, vrijeme); StiglaPoruka?.Invoke(this, nova); }); }
public void Init(string ip) { hubConnection = new HubConnectionBuilder() #if BLAZOR .WithUrl($"http://{ip}:5000/hubs/chat", opt => { opt.LogLevel = SignalRLogLevel.Trace; // Client log level opt.SkipNegotiation = true; opt.Transport = HttpTransportType.WebSockets; // Which transport you want to use for this connection }) #else .WithUrl($"http://{ip}:5000/hubs/chat") #endif .Build(); #if BLAZOR hubConnection.OnClose(async(error) => #else hubConnection.Closed += async(error) => #endif { OnConnectionClosed?.Invoke(this, new MessageEventArgs("Connection closed...")); IsConnected = false; await Task.Delay(random.Next(0, 5) * 1000); try { await ConnectAsync(); } catch (Exception ex) { // Exception! } #if BLAZOR }); #else };
/// <summary> /// Es wurden Daten gelesen /// </summary> /// <param name="ar"></param> private void ReadCallback(IAsyncResult ar) { try { int read; lock (_SerialPortLock) { if (_port.IsOpen) { read = _port.BaseStream.EndRead(ar); StateObj state = (StateObj)ar.AsyncState; OnDataReceived?.Invoke(state.data, read); } } StartRead(); } //Die Verbindung wurde beendet catch (IOException) { OnConnectionClosed?.Invoke(this); //_port.Close(); } catch (Exception) { } }
protected override void OnClose(CloseEventArgs e) { OnConnectionClosed?.Invoke(this); }
protected virtual void ConnectionClosed(object sender, ConnectionInfo connectionInfo) { OnConnectionClosed?.Invoke(sender, connectionInfo); }
internal override void RemoveConnection(FSWPage page) { base.RemoveConnection(page); OnConnectionClosed?.Invoke((T)page); }
private void _webSocket_OnClosed(object sender, System.Net.WebSockets.WebSocketCloseStatus reason) { OnConnectionClosed?.Invoke(this, System.EventArgs.Empty); }
public void Init(string urlRoot, string portNumber, bool useHttps) { //-----ITvitae server url = "10.10.1.34"-----// //-----ITvitae server port = "4444"-----// string url = $"http{(useHttps ? "s" : String.Empty)}://{urlRoot}:{portNumber}/hubs/chat"; //string url = $"http://{urlRoot}:{portNumber}/hubs/chat"; // Setup the hubconnection with the newly created url hubConnection = new HubConnectionBuilder() .WithUrl(url) .Build(); // Initialize random so we can use it to randomize colors random = new Random(); // Setup the hubConnection events hubConnection.Closed += async(error) => { OnConnectionClosed?.Invoke(this, new MessageEventArgs("Connection closed...", DateTime.Now, string.Empty)); IsConnected = false; // Wait a little and try to reconnect await Task.Delay(random.Next(0, 5) * 1000); try { await ConnectAsync(); } catch (Exception ex) { Debug.WriteLine(ex); } }; // Receive message hubConnection.On <string, DateTime, string>("ReceiveMessage", (user, dateTime, message) => { OnReceivedMessage?.Invoke(this, new MessageEventArgs(user, dateTime, message)); }); // Receive file hubConnection.On <string, DateTime, string, string>("ReceiveFile", (user, dateTime, folderName, fileName) => { OnReceivedFile?.Invoke(this, new FileEventArgs(user, dateTime, folderName, fileName)); }); // Entered hubConnection.On <string, DateTime>("Entered", (user, dateTime) => { OnEnteredOrExited?.Invoke(this, new MessageEventArgs(user, dateTime, $"{user} entered.")); }); // Exited hubConnection.On <string, DateTime>("Left", (user, dateTime) => { OnEnteredOrExited?.Invoke(this, new MessageEventArgs(user, dateTime, $"{user} left.")); }); // Entered or left ??? <--- WTF (vanuit tutorial, geen idee waar voor nodig) hubConnection.On <string, DateTime>("EnteredOrLeft", (message, dateTime) => { OnEnteredOrExited?.Invoke(this, new MessageEventArgs("???Someone???", dateTime, message)); }); }
private Task HubConnection_Closed(Exception arg) { OnConnectionClosed.Invoke(this, null); return(Task.CompletedTask); }
private Task connection_Closed(Exception arg) { OnConnectionClosed?.Invoke(this, null); Connected = false; return(Task.CompletedTask); }
/// <summary> /// /// </summary> /// <param name="aClosedByServer"></param> protected void TriggerOnConnectionClosed(bool aClosedByServer) { OnConnectionClosed?.Invoke(this, aClosedByServer); }