#pragma warning disable 1998 public async Task DisconnectInternal(Exception ifErrorWhy) { if (disconnecting) { return; } if (connection != null && connection.State == HubConnectionState.Connected) { SendMessageToAll("I_AM_OUTTA_HERE", string.Empty, true).Wait(1000); disconnecting = true; disconnectingCancel.Cancel(); #if !UNITY_2018_3_OR_NEWER await connection.DisposeAsync(); #else var tt = connection.DisposeAsync(); #endif } if (!disconnecting) { disconnecting = true; disconnectingCancel.Cancel(); } try { connection = null; if (httpClient != null) { httpClient.Dispose(); httpClient = null; } ConnectionChanged?.Invoke(this, false, ifErrorWhy); } finally { peers.Clear(); UserId = string.Empty; ClientUrl = string.Empty; ClientToken = string.Empty; MessageToken = string.Empty; Me = null; disconnectingCancel = new CancellationTokenSource(); disconnecting = false; } }
private void Client_NewPeer(Microsoft.SignalNow.Client.SignalNowClient signalNow, Microsoft.SignalNow.Client.SignalNowPeer newPeer) { Debug.Log($"Peer {newPeer.UserName} is {newPeer.Status}");; }
void Client_PeerStatusChanged(Microsoft.SignalNow.Client.SignalNowClient signalNow, Microsoft.SignalNow.Client.SignalNowPeer peer) { Debug.Log($"Peer {peer.UserName} is {peer.Status}"); }
private void OnMessageIn(string senderId, string messageType, string messagePayload) { if (disconnecting) { return; } DateTime messageTime = DateTime.UtcNow; if (messageType.Equals("I_AM_HERE", StringComparison.InvariantCultureIgnoreCase)) { TimeSpan statusExpirationTimeout = TimeSpan.FromSeconds(int.Parse(messagePayload)); bool newPeer = true; if (peers.ContainsKey(senderId)) { newPeer = false; peers[senderId].Resurrect(); PeerStatusChanged?.Invoke(this, peers[senderId]); } string response = $"[\"{(int)Me.StatusExpirationTimeout.TotalSeconds}\", \"{Me.Status.ToString()}\"]"; SendImportantMessage(senderId, false, "HELLO", response, true) .ContinueWith((res) => { if (newPeer) { peers[senderId] = new SignalNowPeer(senderId, PeerStatus.Online, statusExpirationTimeout); NewPeer?.Invoke(this, peers[senderId]); } }); } else if (messageType.Equals("HELLO", StringComparison.InvariantCultureIgnoreCase)) { JArray paramArray = JArray.Parse(messagePayload); var timeoutStr = paramArray[0].ToString(); var statusStr = paramArray[1].ToString(); TimeSpan statusExpirationTimeout = TimeSpan.FromSeconds(int.Parse(timeoutStr)); PeerStatus status = (PeerStatus)Enum.Parse(typeof(PeerStatus), statusStr, true); if (!peers.ContainsKey(senderId)) { peers[senderId] = new SignalNowPeer(senderId, status, statusExpirationTimeout); NewPeer?.Invoke(this, peers[senderId]); } else { peers[senderId].LastStatusTime = messageTime; peers[senderId].Status = status; peers[senderId].StatusExpirationTimeout = statusExpirationTimeout; PeerStatusChanged?.Invoke(this, peers[senderId]); } } else if (messageType.Equals("I_AM_OUTTA_HERE", StringComparison.InvariantCultureIgnoreCase)) { if (peers.ContainsKey(senderId)) { peers[senderId].Status = PeerStatus.Offline; PeerStatusChanged?.Invoke(this, peers[senderId]); #if UNITY_2018_2_OR_NEWER UnityEngine.Debug.Log($"{senderId} quit."); #else System.Diagnostics.Debug.WriteLine($"{senderId} quit."); #endif } } else { // only respect messages from peers we had a handshake with if (peers.ContainsKey(senderId)) { peers[senderId].LastDataMessageTime = messageTime; peers[senderId].LastStatusTime = messageTime; if (messageType.Equals("STILL_HERE", StringComparison.InvariantCultureIgnoreCase)) { PeerStatus status = (PeerStatus)Enum.Parse(typeof(PeerStatus), messagePayload, true); peers[senderId].Status = status; } else { Task.Run(() => { NewMessage?.Invoke(this, senderId, messageType, messagePayload); }); } } } }
public async Task <bool> Connect(string userName, string deviceId, string companyName, string teamName, string authServiceToken, string authServiceName) { if (httpClient == null) { httpClient = new SignalNowHttp(serverAddress, (string msg, Exception ex) => { RequestFailed?.Invoke(this, msg); }); } string responseString = string.Empty; UserId = string.Empty; ClientUrl = string.Empty; ClientToken = string.Empty; TurnServersAuthorization = string.Empty; MessageToken = string.Empty; MessageTokenValidTo = DateTime.MinValue; AuthService = authServiceName; peers.Clear(); if (connection != null) { if (connection.State == HubConnectionState.Connected) { await Disconnect(); } connection = null; } using (HttpRequestMessage request = httpClient.CreateHttpRequest("/api/Negotiate", HttpMethod.Post)) { request.Headers.Add("username", userName); request.Headers.Add("deviceid", deviceId); request.Headers.Add("companyname", companyName); request.Headers.Add("teamname", teamName); request.Headers.Add("authservicetoken", authServiceToken); request.Headers.Add("authservicename", authServiceName); #if UNITY_2018_2_OR_NEWER UnityEngine.Debug.Log($"Connecting to {serverAddress}."); #else System.Diagnostics.Debug.WriteLine($"Connecting to {serverAddress}."); #endif responseString = await httpClient.SendRequestLiteWithResultAsync(request); if (responseString == null) { return(false); // no need to handle the error because already done } #if UNITY_2018_2_OR_NEWER UnityEngine.Debug.Log($"!!! Connected to {serverAddress}."); #else System.Diagnostics.Debug.WriteLine($"!!! Connected to {serverAddress}."); #endif } //userId, clientToken, clientUrl, serverTimeString, turnServersAuthorization JArray paramArray = JArray.Parse(responseString); UserId = paramArray[0].ToString(); ClientToken = paramArray[1].ToString(); ClientUrl = paramArray[2].ToString(); var serverTimeString = paramArray[3].ToString(); ClientServerTimeDiff = DateTime.UtcNow - UnixEpoch.AddSeconds(long.Parse(serverTimeString)); if (paramArray.Count > 4) { TurnServersAuthorization = paramArray[4].ToString(); } #if UNITY_2018_2_OR_NEWER UnityEngine.Debug.Log($"Initializing SignalR connection {ClientUrl}."); #else System.Diagnostics.Debug.WriteLine($"Initializing SignalR connection {ClientUrl}."); #endif connection = new HubConnectionBuilder() .WithUrl(ClientUrl, option => { option.AccessTokenProvider = () => { return(Task.FromResult(ClientToken)); }; }) #if !UNITY_2018_2_OR_NEWER .AddMessagePackProtocol() // https://fogbugz.unity3d.com/default.asp?1091189_1sqkebcrot7vvv9b #endif .Build(); #if UNITY_2018_2_OR_NEWER UnityEngine.Debug.Log($"Connecting to SignalR..."); #else System.Diagnostics.Debug.WriteLine($"Connecting to SignalR..."); #endif await connection.StartAsync(); bool bRes = (connection.State == HubConnectionState.Connected); if (bRes) { Me = new SignalNowPeer(UserId, PeerStatus.Online, StatusTimeout); connection.Closed += (Exception why) => { #if UNITY_2018_2_OR_NEWER UnityEngine.Debug.LogWarning($"SignalR disconnected"); #else System.Diagnostics.Debug.WriteLine($"SignalR disconnected"); #endif connection = null; if (!disconnecting) { return(DisconnectInternal(why)); } else { return(Task.Delay(0)); } }; #if UNITY_2018_2_OR_NEWER UnityEngine.Debug.Log($"Getting a message token."); #else System.Diagnostics.Debug.WriteLine($"Getting a message token."); #endif bRes = await EnsureMessageToken(); #if UNITY_2018_2_OR_NEWER UnityEngine.Debug.Log($"Message token is {(bRes ? "good" : "empty")}"); #else System.Diagnostics.Debug.WriteLine($"Message token is {(bRes ? "good" : "empty")}"); #endif if (bRes) { connection.On <string, string, string>("SIGNAL", (string senderId, string messageType, string messagePayload) => { if (senderId != UserId) { OnMessageIn(senderId, messageType, messagePayload); } }); ConnectionChanged?.Invoke(this, true, null); bRes = await SendImportantMessage(GetEveryoneRecipient(), true, "I_AM_HERE", ((int)StatusTimeout.TotalSeconds).ToString(), true); } } else { #if UNITY_2018_2_OR_NEWER UnityEngine.Debug.Log($"Couldn't connect to SignalR."); #else System.Diagnostics.Debug.WriteLine($"Couldn't connect to SignalR."); #endif } return(bRes); }