Beispiel #1
0
        internal static void ProcessResponseCallbackWebExceptionHandler <T> (WebException webEx, RequestState <T> asynchRequestState,
                                                                             PubnubErrorFilter.Level errorLevel)
        {
            #if (ENABLE_PUBNUB_LOGGING)
            if (webEx.ToString().Contains("Aborted"))
            {
                LoggingMethod.WriteToLog(string.Format("DateTime {0}, ProcessResponseCallbackWebExceptionHandler WebException: {1}", DateTime.Now.ToString(), webEx.ToString()), LoggingMethod.LevelInfo);
            }
            else
            {
                LoggingMethod.WriteToLog(string.Format("DateTime {0}, ProcessResponseCallbackWebExceptionHandler WebException: {1}", DateTime.Now.ToString(), webEx.ToString()), LoggingMethod.LevelError);
            }
            #endif

            UrlRequestCommonExceptionHandler <T> (webEx.Message, asynchRequestState, asynchRequestState.Timeout,
                                                  false, errorLevel);
        }
Beispiel #2
0
 internal static void ResponseCallbackExceptionHandler <T> (CustomEventArgs <T> cea, RequestState <T> requestState,
                                                            Exception ex, PubnubErrorFilter.Level errorLevel)
 {
     #if (ENABLE_PUBNUB_LOGGING)
     LoggingMethod.WriteToLog(string.Format("DateTime {0}, Process Response Exception: = {1}", DateTime.Now.ToString(), ex.ToString()), LoggingMethod.LevelError);
     #endif
     if (requestState.ChannelEntities != null)
     {
         if (requestState.RespType.Equals(ResponseType.SubscribeV2) ||
             requestState.RespType.Equals(ResponseType.PresenceV2)
             )
         {
             PubnubCallbacks.FireErrorCallbacksForAllChannels(ex, requestState,
                                                              PubnubErrorSeverity.Warn, PubnubErrorCode.None, errorLevel);
         }
         else
         {
             PubnubCallbacks.FireErrorCallbacksForAllChannels <T> (ex, requestState,
                                                                   PubnubErrorSeverity.Critical, PubnubErrorCode.None, errorLevel);
         }
     }
     ProcessResponseCallbackExceptionHandler <T> (ex, requestState, errorLevel);
 }
Beispiel #3
0
 internal static void ProcessResponseCallbackExceptionHandler <T> (Exception ex, RequestState <T> asynchRequestState,
                                                                   PubnubErrorFilter.Level errorLevel)
 {
     #if (ENABLE_PUBNUB_LOGGING)
     LoggingMethod.WriteToLog(string.Format("DateTime {0}, ProcessResponseCallbackExceptionHandler Exception= {1} for URL: {2}",
                                            DateTime.Now.ToString(), ex.ToString(),
                                            (asynchRequestState.Request != null)?asynchRequestState.Request.RequestUri.ToString(): "asynchRequestState.Request null"),
                              LoggingMethod.LevelInfo);
     #endif
     UrlRequestCommonExceptionHandler <T> (ex.Message, asynchRequestState, asynchRequestState.Timeout,
                                           false, errorLevel);
 }
Beispiel #4
0
 internal static void ResponseCallbackWebExceptionHandler <T> (CustomEventArgs <T> cea, RequestState <T> requestState,
                                                               WebException webEx, string channel, SafeDictionary <PubnubChannelCallbackKey, object> channelCallbacks,
                                                               PubnubErrorFilter.Level errorLevel)
 {
     if (requestState.Channels != null || requestState.RespType == ResponseType.Time)
     {
         if (requestState.RespType == ResponseType.Subscribe ||
             requestState.RespType == ResponseType.Presence)
         {
             if (webEx.Message.IndexOf("The request was aborted: The request was canceled") == -1 ||
                 webEx.Message.IndexOf("Machine suspend mode enabled. No request will be processed.") == -1)
             {
                 PubnubCallbacks.FireErrorCallbacksForAllChannels <T> (webEx, requestState,
                                                                       PubnubErrorSeverity.Warn, channelCallbacks,
                                                                       true, errorLevel);
             }
         }
         else
         {
             PubnubCallbacks.CallErrorCallback <T> (webEx, requestState, channel,
                                                    PubnubErrorSeverity.Warn, requestState.ErrorCallback, errorLevel);
         }
     }
     ProcessResponseCallbackWebExceptionHandler <T> (webEx, requestState, channel, errorLevel);
 }
Beispiel #5
0
 internal static void ResponseCallbackWebExceptionHandler <T> (CustomEventArgs <T> cea, RequestState <T> requestState,
                                                               WebException webEx,
                                                               PubnubErrorFilter.Level errorLevel)
 {
     if ((requestState != null) && (requestState.ChannelEntities != null || requestState.RespType != ResponseType.Time))
     {
         if (requestState.RespType.Equals(ResponseType.SubscribeV2) ||
             requestState.RespType.Equals(ResponseType.PresenceV2)
             )
         {
             if (webEx.Message.IndexOf("The request was aborted: The request was canceled") == -1 ||
                 webEx.Message.IndexOf("Machine suspend mode enabled. No request will be processed.") == -1)
             {
                 PubnubCallbacks.FireErrorCallbacksForAllChannels <T> (webEx, requestState,
                                                                       PubnubErrorSeverity.Warn, errorLevel);
             }
         }
         else
         {
             PubnubCallbacks.FireErrorCallbacksForAllChannels <T> (webEx, requestState,
                                                                   PubnubErrorSeverity.Warn, errorLevel);
         }
     }
     ProcessResponseCallbackWebExceptionHandler <T> (webEx, requestState, errorLevel);
 }
Beispiel #6
0
        private void StartCoroutinesByName <T> (string url, RequestState <T> pubnubRequestState, int timeout, int pause, CurrentRequestType crt)
        {
            CoroutineParams <T> cp = new CoroutineParams <T> (url, timeout, pause, crt, typeof(T), pubnubRequestState);

            if (crt == CurrentRequestType.Subscribe)
            {
                if ((SubTimeoutCoroutine != null) && (!isSubscribeComplete))
                {
                    StopCoroutine(SubTimeoutCoroutine);
                    #if (ENABLE_PUBNUB_LOGGING)
                    LoggingMethod.WriteToLog(string.Format("DateTime {0}, Stopped existing timeout coroutine {1}", DateTime.Now.ToString(), cp.crt.ToString()), LoggingMethod.LevelInfo);
                    #endif
                }

                SubTimeoutCoroutine = CheckTimeoutSub <T> (cp);
                SubCoroutine        = SendRequestSub <T> (cp);
                StartCoroutine(SubTimeoutCoroutine);
                StartCoroutine(SubCoroutine);
            }
            else if (crt == CurrentRequestType.NonSubscribe)
            {
                if ((NonSubTimeoutCoroutine != null) && (!isNonSubscribeComplete))
                {
                    StopCoroutine(NonSubTimeoutCoroutine);
                    #if (ENABLE_PUBNUB_LOGGING)
                    LoggingMethod.WriteToLog(string.Format("DateTime {0}, Stopped existing timeout coroutine {1}", DateTime.Now.ToString(), cp.crt.ToString()), LoggingMethod.LevelInfo);
                    #endif
                }

                NonSubTimeoutCoroutine = CheckTimeoutNonSub <T> (cp);
                NonSubCoroutine        = SendRequestNonSub <T> (cp);
                StartCoroutine(NonSubTimeoutCoroutine);
                StartCoroutine(NonSubCoroutine);
            }
            else if (crt == CurrentRequestType.PresenceHeartbeat)
            {
                if ((PresenceHeartbeatTimeoutCoroutine != null) && (!isPresenceHeartbeatComplete))
                {
                    StopCoroutine(PresenceHeartbeatTimeoutCoroutine);
                    #if (ENABLE_PUBNUB_LOGGING)
                    LoggingMethod.WriteToLog(string.Format("DateTime {0}, Stopped existing timeout coroutine {1}", DateTime.Now.ToString(), cp.crt.ToString()), LoggingMethod.LevelInfo);
                    #endif
                }

                PresenceHeartbeatTimeoutCoroutine = CheckTimeoutPresenceHeartbeat <T> (cp);
                PresenceHeartbeatCoroutine        = SendRequestPresenceHeartbeat <T> (cp);
                StartCoroutine(PresenceHeartbeatTimeoutCoroutine);
                StartCoroutine(PresenceHeartbeatCoroutine);
            }
            else if (crt == CurrentRequestType.Heartbeat)
            {
                if ((HeartbeatTimeoutCoroutine != null) && (!isHearbeatComplete))
                {
                    StopCoroutine(HeartbeatTimeoutCoroutine);
                    #if (ENABLE_PUBNUB_LOGGING)
                    LoggingMethod.WriteToLog(string.Format("DateTime {0}, Stopped existing timeout coroutine {1}", DateTime.Now.ToString(), cp.crt.ToString()), LoggingMethod.LevelInfo);
                    #endif
                }

                HeartbeatTimeoutCoroutine = CheckTimeoutHeartbeat <T> (cp);
                HeartbeatCoroutine        = SendRequestHeartbeat <T> (cp);
                StartCoroutine(HeartbeatTimeoutCoroutine);
                StartCoroutine(HeartbeatCoroutine);
            }
        }
Beispiel #7
0
        internal static void ResponseCallbackErrorOrTimeoutHandler <T> (CustomEventArgs <T> cea, RequestState <T> requestState, string channel,
                                                                        PubnubErrorFilter.Level errorLevel, IJsonPluggableLibrary jsonPluggableLibrary)
        {
            WebException webEx = new WebException(cea.Message);

            if ((cea.Message.Contains("NameResolutionFailure") ||
                 cea.Message.Contains("ConnectFailure") ||
                 cea.Message.Contains("ServerProtocolViolation") ||
                 cea.Message.Contains("ProtocolError")
                 ))
            {
                webEx = new WebException("Network connnect error", WebExceptionStatus.ConnectFailure);

                PubnubCallbacks.CallErrorCallback <T> (cea.Message, null, channel,
                                                       PubnubErrorCode.NoInternetRetryConnect, PubnubErrorSeverity.Warn, requestState.ErrorCallback, errorLevel);
            }
            else if (cea.IsTimeout || Utility.CheckRequestTimeoutMessageInError(cea))
            {
            }
            else if ((cea.Message.Contains("403")) ||
                     (cea.Message.Contains("java.io.FileNotFoundException")) ||
                     ((PubnubUnity.Version.Contains("UnityWeb")) && (cea.Message.Contains("Failed downloading"))))
            {
                PubnubClientError error = new PubnubClientError(403, PubnubErrorSeverity.Critical, cea.Message, PubnubMessageSource.Server, requestState.Request, requestState.Response, cea.Message, channel);
                PubnubCallbacks.GoToCallback(error, requestState.ErrorCallback, jsonPluggableLibrary);
            }
            else if (cea.Message.Contains("500"))
            {
                PubnubClientError error = new PubnubClientError(500, PubnubErrorSeverity.Critical, cea.Message, PubnubMessageSource.Server, requestState.Request, requestState.Response, cea.Message, channel);
                PubnubCallbacks.GoToCallback(error, requestState.ErrorCallback, jsonPluggableLibrary);
            }
            else if (cea.Message.Contains("502"))
            {
                PubnubClientError error = new PubnubClientError(503, PubnubErrorSeverity.Critical, cea.Message, PubnubMessageSource.Server, requestState.Request, requestState.Response, cea.Message, channel);
                PubnubCallbacks.GoToCallback(error, requestState.ErrorCallback, jsonPluggableLibrary);
            }
            else if (cea.Message.Contains("503"))
            {
                PubnubClientError error = new PubnubClientError(503, PubnubErrorSeverity.Critical, cea.Message, PubnubMessageSource.Server, requestState.Request, requestState.Response, cea.Message, channel);
                PubnubCallbacks.GoToCallback(error, requestState.ErrorCallback, jsonPluggableLibrary);
            }
            else if (cea.Message.Contains("504"))
            {
                PubnubClientError error = new PubnubClientError(504, PubnubErrorSeverity.Critical, cea.Message, PubnubMessageSource.Server, requestState.Request, requestState.Response, cea.Message, channel);
                PubnubCallbacks.GoToCallback(error, requestState.ErrorCallback, jsonPluggableLibrary);
            }
            else if (cea.Message.Contains("414"))
            {
                PubnubClientError error = new PubnubClientError(414, PubnubErrorSeverity.Critical, cea.Message, PubnubMessageSource.Server, requestState.Request, requestState.Response, cea.Message, channel);
                PubnubCallbacks.GoToCallback(error, requestState.ErrorCallback, jsonPluggableLibrary);
            }
            else
            {
                PubnubClientError error = new PubnubClientError(400, PubnubErrorSeverity.Critical, cea.Message, PubnubMessageSource.Server, requestState.Request, requestState.Response, cea.Message, channel);
                PubnubCallbacks.GoToCallback(error, requestState.ErrorCallback, jsonPluggableLibrary);
            }
            ProcessResponseCallbackWebExceptionHandler <T> (webEx, requestState, channel, errorLevel);
        }
 internal static void FireErrorCallbacksForAllChannels <T> (WebException webEx, RequestState <T> requestState,
                                                            PubnubErrorSeverity severity, PubnubErrorFilter.Level errorLevel)
 {
     foreach (ChannelEntity channelEntity in requestState.ChannelEntities)
     {
         PubnubClientError error = Helpers.CreatePubnubClientError <T> (webEx, requestState, channelEntity.ChannelID.ChannelOrChannelGroupName,
                                                                        severity);
         FireErrorCallback <T> (channelEntity,
                                errorLevel, error);
     }
 }
        internal static void FireErrorCallbacksForAllChannelsCommon <T>(Exception ex, string message, RequestState <T> requestState,
                                                                        List <ChannelEntity> channelEntities,
                                                                        PubnubErrorSeverity severity, PubnubErrorCode errorType,
                                                                        ResponseType responseType, PubnubErrorFilter.Level errorLevel)
        {
            if ((channelEntities != null) && (channelEntities.Count > 0))
            {
                foreach (ChannelEntity channelEntity in channelEntities)
                {
                    string channel      = "";
                    string channelGroup = "";
                    if (channelEntity.ChannelID.IsChannelGroup)
                    {
                        channelGroup = channelEntity.ChannelID.ChannelOrChannelGroupName;
                    }
                    else
                    {
                        channel = channelEntity.ChannelID.ChannelOrChannelGroupName;
                    }

                    PubnubClientError error = null;
                    if (ex != null)
                    {
                        error = Helpers.CreatePubnubClientError <T> (ex, requestState, errorType,
                                                                     severity, channel, channelGroup);
                    }
                    else
                    {
                        error = Helpers.CreatePubnubClientError <T> (message, requestState, errorType,
                                                                     severity, channel, channelGroup);
                    }

                    FireErrorCallback <T> (channelEntity,
                                           errorLevel, error);
                }
            }

            else
            {
                if ((requestState != null) && (requestState.ErrorCallback != null))
                {
                    PubnubClientError error = null;
                    if (ex != null)
                    {
                        error = Helpers.CreatePubnubClientError <T> (ex, requestState, errorType,
                                                                     severity, "", "");
                    }
                    else
                    {
                        error = Helpers.CreatePubnubClientError <T> (message, requestState, errorType,
                                                                     severity, "", "");
                    }

                    GoToCallback(error, requestState.ErrorCallback, errorLevel);
                }
                #if (ENABLE_PUBNUB_LOGGING)
                else
                {
                    LoggingMethod.WriteToLog(string.Format("DateTime {0}, FireErrorCallbacksForAllChannelsCommon: {1}",
                                                           DateTime.Now.ToString(),
                                                           (requestState != null)?"ErrorCallback null":"requestState null"
                                                           ), LoggingMethod.LevelInfo);
                }
                LoggingMethod.WriteToLog(string.Format("DateTime {0}, FireErrorCallbacksForAllChannelsCommon: channelEntities count: {1}",
                                                       DateTime.Now.ToString(),
                                                       (channelEntities != null)?channelEntities.Count.ToString():"channelEntities null"
                                                       ), LoggingMethod.LevelInfo);
                #endif
            }
        }
 protected override PubnubWebRequest SetTimeout <T> (RequestState <T> pubnubRequestState, PubnubWebRequest request)
 {
     request.Timeout = GetTimeoutInSecondsForResponseType(pubnubRequestState.Type) * 1000;
     return(request);
 }
        void ConnectToHostAndSendRequest <T> (bool sslEnabled, TcpClient tcpClient, RequestState <T> pubnubRequestState, string requestString)
        {
            NetworkStream stream = tcpClient.GetStream();

            string proxyAuth = string.Format("{0}:{1}", Proxy.ProxyUserName, Proxy.ProxyPassword);

            byte[] proxyAuthBytes = Encoding.UTF8.GetBytes(proxyAuth);

            //Proxy-Authenticate: authentication mode Basic, Digest and NTLM
            string connectRequest = "";

            if (sslEnabled)
            {
                connectRequest = string.Format("CONNECT {0}:443  HTTP/1.1\r\nProxy-Authorization: Basic {1}\r\nHost: {0}\r\n\r\n", this._domainName, Convert.ToBase64String(proxyAuthBytes));
            }
            else
            {
                connectRequest = string.Format("CONNECT {0}:80  HTTP/1.1\r\nProxy-Authorization: Basic {1}\r\nHost: {0}\r\n\r\n", this._domainName, Convert.ToBase64String(proxyAuthBytes));
            }

            byte[] tunnelRequest = Encoding.UTF8.GetBytes(connectRequest);
            stream.Write(tunnelRequest, 0, tunnelRequest.Length);
            stream.Flush();

            stream.ReadTimeout = pubnubRequestState.Request.Timeout * 5;

            StateObject <T> state = new StateObject <T> ();

            state.tcpClient     = tcpClient;
            state.RequestState  = pubnubRequestState;
            state.requestString = requestString;
            state.netStream     = stream;

            //stream.BeginRead(state.buffer, 0, state.buffer.Length, new AsyncCallback(ConnectToHostAndSendRequestCallback<T>), state);

            StringBuilder response       = new StringBuilder();
            var           responseStream = new StreamReader(stream);

            char[] buffer = new char[2048];

            int  charsRead       = responseStream.Read(buffer, 0, buffer.Length);
            bool connEstablished = false;

            while (charsRead > 0)
            {
                response.Append(buffer);
                if ((response.ToString().IndexOf("200 Connection established") > 0) || (response.ToString().IndexOf("200 OK") > 0))
                {
                    connEstablished = true;
                    break;
                }
                charsRead = responseStream.Read(buffer, 0, buffer.Length);
            }

            if (connEstablished)
            {
                if (sslEnabled)
                {
                    SendSslRequest <T> (stream, tcpClient, pubnubRequestState, requestString);
                }
                else
                {
                    SendRequest <T> (tcpClient, pubnubRequestState, requestString);
                }
            }
            else if (response.ToString().IndexOf("407 Proxy Authentication Required") > 0)
            {
                int    pos  = response.ToString().IndexOf("Proxy-Authenticate");
                string desc = "";
                if (pos > 0)
                {
                    desc = response.ToString().Substring(pos, response.ToString().IndexOf("\r\n", pos) - pos);
                }
                throw new WebException(string.Format("Proxy Authentication Required. Desc: {0}", desc));
            }
            else
            {
                throw new WebException("Couldn't connect to the server");
            }
        }
Beispiel #12
0
        internal static void FireErrorCallbacksForAllChannels <T> (WebException webEx, RequestState <T> requestState,
                                                                   PubnubErrorSeverity severity, SafeDictionary <PubnubChannelCallbackKey,
                                                                                                                 object> channelCallbacks, bool callbackObjectType, PubnubErrorFilter.Level errorLevel)
        {
            for (int index = 0; index < requestState.Channels.Length; index++)
            {
                string            activeChannel = requestState.Channels [index].ToString();
                PubnubClientError error         = Helpers.CreatePubnubClientError <T> (webEx, requestState, activeChannel,
                                                                                       severity);

                FireErrorCallback <T> (activeChannel, channelCallbacks,
                                       callbackObjectType, requestState.RespType, errorLevel, error);
            }
        }
Beispiel #13
0
 public CoroutineParams(string url, int timeout, int pause, CurrentRequestType crt, Type typeParameterType, RequestState <T> requestState)
 {
     this.url               = url;
     this.timeout           = timeout;
     this.pause             = pause;
     this.crt               = crt;
     this.typeParameterType = typeParameterType;
     this.requestState      = requestState;
 }
Beispiel #14
0
        public IEnumerator DelayRequest <T> (string url, RequestState <T> pubnubRequestState, int timeout, int pause, CurrentRequestType crt)
        {
            yield return(new WaitForSeconds(pause));

            StartCoroutinesByName <T> (url, pubnubRequestState, timeout, pause, crt);
        }
Beispiel #15
0
        internal static void CreateErrorCodeAndCallErrorCallback <T> (int statusCode, CustomEventArgs <T> cea, RequestState <T> requestState,
                                                                      PubnubErrorFilter.Level errorLevel)
        {
            PubnubClientError error = new PubnubClientError(statusCode, PubnubErrorSeverity.Critical, cea.Message, PubnubMessageSource.Server,
                                                            requestState.Request, requestState.Response, cea.Message, requestState.ChannelEntities);

            PubnubCallbacks.CallErrorCallback <T> (requestState.ErrorCallback, requestState.ChannelEntities,
                                                   error, errorLevel);
        }
        internal static void SendCallbacks <T>(IJsonPluggableLibrary jsonPluggableLibrary, RequestState <T> asynchRequestState,
                                               List <object> itemMessage, CallbackType callbackType, bool checkType)
        {
            if (asynchRequestState.ChannelEntities != null)
            {
                SendCallbacks <T> (jsonPluggableLibrary, asynchRequestState.ChannelEntities, itemMessage, callbackType, checkType);
            }
            else
            {
                #if (ENABLE_PUBNUB_LOGGING)
                LoggingMethod.WriteToLog(string.Format("DateTime {0}, SendCallbacks1: Callback type={1}", DateTime.Now.ToString(), callbackType.ToString()), LoggingMethod.LevelInfo);
                #endif

                if (callbackType.Equals(CallbackType.Success))
                {
                    GoToCallback <T> (itemMessage, asynchRequestState.SuccessCallback, jsonPluggableLibrary);
                }
            }
        }
Beispiel #17
0
        internal static void ResponseCallbackErrorOrTimeoutHandler <T> (CustomEventArgs <T> cea, RequestState <T> requestState,
                                                                        PubnubErrorFilter.Level errorLevel)
        {
            WebException webEx = new WebException(cea.Message);

            if ((cea.Message.Contains("NameResolutionFailure") ||
                 cea.Message.Contains("ConnectFailure") ||
                 cea.Message.Contains("ServerProtocolViolation") ||
                 cea.Message.Contains("ProtocolError")
                 ))
            {
                webEx = new WebException("Network connnect error", WebExceptionStatus.ConnectFailure);

                PubnubCallbacks.FireErrorCallbacksForAllChannels <T> (cea.Message, requestState,
                                                                      PubnubErrorSeverity.Warn, PubnubErrorCode.NoInternetRetryConnect, errorLevel);
            }
            else if (cea.IsTimeout || Utility.CheckRequestTimeoutMessageInError(cea))
            {
            }
            else if ((cea.Message.Contains("403")) ||
                     (cea.Message.Contains("java.io.FileNotFoundException")) ||
                     ((PubnubUnity.Version.Contains("UnityWeb")) && (cea.Message.Contains("Failed downloading"))))
            {
                CreateErrorCodeAndCallErrorCallback <T> (403, cea, requestState, errorLevel);
            }
            else if (cea.Message.Contains("500"))
            {
                CreateErrorCodeAndCallErrorCallback <T> (500, cea, requestState, errorLevel);
            }
            else if (cea.Message.Contains("502"))
            {
                CreateErrorCodeAndCallErrorCallback <T> (502, cea, requestState, errorLevel);
            }
            else if (cea.Message.Contains("503"))
            {
                CreateErrorCodeAndCallErrorCallback <T> (503, cea, requestState, errorLevel);
            }
            else if (cea.Message.Contains("504"))
            {
                CreateErrorCodeAndCallErrorCallback <T> (504, cea, requestState, errorLevel);
            }
            else if (cea.Message.Contains("414"))
            {
                CreateErrorCodeAndCallErrorCallback <T> (414, cea, requestState, errorLevel);
            }
            else if (cea.Message.Contains("451"))
            {
                CreateErrorCodeAndCallErrorCallback <T> (451, cea, requestState, errorLevel);
            }
            else if (cea.Message.Contains("481"))
            {
                CreateErrorCodeAndCallErrorCallback <T> (481, cea, requestState, errorLevel);
            }
            else
            {
                CreateErrorCodeAndCallErrorCallback <T> (400, cea, requestState, errorLevel);
            }
            ProcessResponseCallbackWebExceptionHandler <T> (webEx, requestState, errorLevel);
        }
Beispiel #18
0
        private void ConnectToHostAndSendRequestCallback <T>(IAsyncResult asynchronousResult)
        {
            StateObject <T>  asynchStateObject  = asynchronousResult.AsyncState as StateObject <T>;
            RequestState <T> asynchRequestState = asynchStateObject.RequestState;

            string channels = "";

            if (asynchRequestState != null && asynchRequestState.Channels != null)
            {
                channels = string.Join(",", asynchRequestState.Channels);
            }

            try
            {
                string    requestString = asynchStateObject.requestString;
                TcpClient tcpClient     = asynchStateObject.tcpClient;

                NetworkStream netStream = asynchStateObject.netStream;
                int           bytesRead = netStream.EndRead(asynchronousResult);

                if (bytesRead > 0)
                {
                    asynchStateObject.sb.Append(Encoding.ASCII.GetString(asynchStateObject.buffer, 0, bytesRead));

                    netStream.BeginRead(asynchStateObject.buffer, 0, StateObject <T> .BufferSize,
                                        new AsyncCallback(ConnectToHostAndSendRequestCallback <T>), asynchStateObject);
                }
                else
                {
                    string resp = asynchStateObject.sb.ToString();
                    if (resp.IndexOf("200 Connection established") > 0)
                    {
                        SendSslRequest <T>(netStream, tcpClient, asynchRequestState, requestString);
                    }
                    else
                    {
                        throw new WebException("Couldn't connect to the server");
                    }
                }
            }
            catch (WebException webEx)
            {
                if (asynchRequestState != null && asynchRequestState.ErrorCallback != null)
                {
                    Action <PubnubClientError> errorCallback = asynchRequestState.ErrorCallback;

                    CallErrorCallback(PubnubErrorSeverity.Warn, PubnubMessageSource.Client,
                                      channels, errorCallback, webEx, null, null);
                }
                ProcessResponseCallbackWebExceptionHandler <T>(webEx, asynchRequestState, channels);
            }
            catch (Exception ex)
            {
                if (asynchRequestState != null && asynchRequestState.ErrorCallback != null)
                {
                    Action <PubnubClientError> errorCallback = asynchRequestState.ErrorCallback;
                    CallErrorCallback(PubnubErrorSeverity.Warn, PubnubMessageSource.Client,
                                      channels, errorCallback, ex, null, null);
                }
                ProcessResponseCallbackExceptionHandler <T>(ex, asynchRequestState);
            }
        }