Exemplo n.º 1
0
#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;
            }
        }
Exemplo n.º 2
0
        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);
        }