private void OnEndWrite(IAsyncResult ar)
        {
            WebRequestState state = ar.AsyncState as WebRequestState;

            //Console.WriteLine(String.Format("OnEndWrite: id:{0}", state.WebRequestId.ToString()));

            HttpWebRequest req           = state.WebRequest as HttpWebRequest;
            Stream         requestStream = state.RequestStream;

            requestStream.EndWrite(ar);
            requestStream.Close();

            IAsyncResult result;

            try
            {
                if (state.IsSessionRequest)
                {
                    result = req.BeginGetResponse(new AsyncCallback(this.OnGetSessionRequestResponse), state);
                }
                else
                {
                    result = req.BeginGetResponse(new AsyncCallback(this.OnGetResponse), state);
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.Message);
            }
        }
        public void TimeOutGetRequestStream(Object stateObj)
        {
            //Console.WriteLine("Web Request timed out");

            WebRequestState state = stateObj as WebRequestState;

            state.TimeOutTimer.Dispose();
            state.Aborted = true;
            state.WebRequest.Abort();
        }
        private void OnGetSessionRequestStream(IAsyncResult ar)
        {
            WebRequestState state = ar.AsyncState as WebRequestState;

            HttpWebRequest req = state.WebRequest as HttpWebRequest;

            Stream outputStream = req.EndGetRequestStream(ar);

            byte[] bytes = Encoding.UTF8.GetBytes(state.Output);

            state.RequestStream = outputStream;
            IAsyncResult result = outputStream.BeginWrite(bytes, 0, bytes.Length, new AsyncCallback(this.OnEndWrite), state);
        }
        private void StartWebRequest(bool retry, string content)
        {
            lock (this)
            {
                webRequestId++;
            }

            waitingRequests++;

            lastSend = DateTime.Now;

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Address);

            WebRequestState state = new WebRequestState(req);

            state.Started      = DateTime.Now;
            state.WebRequestId = webRequestId;

            if (!retry)
            {
                state.Output = BuildPostData();
            }
            else
            {
                state.Output = content;
            }

            req.Method        = METHOD;
            req.ContentType   = CONTENT_TYPE;
            req.Timeout       = m_Wait * 1000;
            req.KeepAlive     = m_KeepAlive;
            req.ContentLength = state.Output.Length;

            // Create the delegate that invokes methods for the timer.
            TimerCallback timerDelegate = new TimerCallback(TimeOutGetRequestStream);
            Timer         timeoutTimer  = new Timer(timerDelegate, state, WEBREQUEST_TIMEOUT, WEBREQUEST_TIMEOUT);

            state.TimeOutTimer = timeoutTimer;

            //Console.WriteLine(String.Format("Start Webrequest: id:{0}", webRequestId.ToString()));
            try
            {
                IAsyncResult result = req.BeginGetRequestStream(new AsyncCallback(this.OnGetRequestStream), state);
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.Message);
            }
        }
//        public void TimeOutGetResponseStream(Object stateObj)
//        {
//#if DEBUG
//            Console.WriteLine("Web Response timed out");
//#endif
//            WebRequestState state = stateObj as WebRequestState;
//            state.TimeOutTimer.Dispose();
//            state.Aborted = true;
//            state.WebRequest.Abort();
//        }

        private void OnGetRequestStream(IAsyncResult ar)
        {
            try
            {
                WebRequestState state = ar.AsyncState as WebRequestState;

                //Console.WriteLine(String.Format("OnGetRequestStream: id:{0}", state.WebRequestId.ToString()));

                if (state.Aborted)
                {
                    waitingRequests--;
                    StartWebRequest(true, state.Output);
                }
                else
                {
                    state.TimeOutTimer.Dispose();
                    HttpWebRequest req = state.WebRequest as HttpWebRequest;

                    Stream requestStream = req.EndGetRequestStream(ar);
                    state.RequestStream = requestStream;
                    //byte[] bytes = Encoding.UTF8.GetBytes(BuildPostData());
                    byte[] bytes = Encoding.UTF8.GetBytes(state.Output);
                    //Console.WriteLine("Write Request:");
                    //Console.WriteLine(state.Output);
                    IAsyncResult result = requestStream.BeginWrite(bytes, 0, bytes.Length, new AsyncCallback(this.OnEndWrite), state);
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.Message);
                waitingRequests--;

                WebRequestState state = ar.AsyncState as WebRequestState;
                StartWebRequest(true, state.Output);
            }
        }
示例#6
0
        private void StartWebRequest(bool retry, string content)
        {
            lock (this)
            {
                webRequestId++;
            }

            waitingRequests++;

            lastSend = DateTime.Now;

            HttpWebRequest req = (HttpWebRequest) WebRequest.Create(Address);

            WebRequestState state = new WebRequestState(req);
            state.Started = DateTime.Now;
            state.WebRequestId = webRequestId;

            if (!retry)
                state.Output = BuildPostData();
            else
                state.Output = content;

            req.Method          = METHOD;
            req.ContentType     = CONTENT_TYPE;
            req.Timeout         = m_Wait * 1000;
            req.KeepAlive       = m_KeepAlive;
            req.ContentLength   = state.Output.Length;

            // Create the delegate that invokes methods for the timer.
            TimerCallback timerDelegate = new TimerCallback(TimeOutGetRequestStream);
            Timer timeoutTimer = new Timer(timerDelegate, state, WEBREQUEST_TIMEOUT, WEBREQUEST_TIMEOUT);
            state.TimeOutTimer = timeoutTimer;

            //Console.WriteLine(String.Format("Start Webrequest: id:{0}", webRequestId.ToString()));
            try
            {
                IAsyncResult result = req.BeginGetRequestStream(new AsyncCallback(this.OnGetRequestStream), state);
            }
            catch(Exception ex)
            {
                //Console.WriteLine(ex.Message);
            }
        }
示例#7
0
        public void RequestBoshSession()
        {
            /*
            Example 1. Requesting a BOSH session

            POST /webclient HTTP/1.1
            Host: httpcm.jabber.org
            Accept-Encoding: gzip, deflate
            Content-Type: text/xml; charset=utf-8
            Content-Length: 104

            <body content='text/xml; charset=utf-8'
                  hold='1'
                  rid='1573741820'
                  to='jabber.org'
                  route='xmpp:jabber.org:9999'
                  secure='true'
                  ver='1.6'
                  wait='60'
                  ack='1'
                  xml:lang='en'
                  xmlns='http://jabber.org/protocol/httpbind'/>
             */

            lastSend = DateTime.Now;

            // Generate the keys
            GenerateKeys();
            rid = GenerateRid();
            Body body = new Body();
            /*
             * <body hold='1' xmlns='http://jabber.org/protocol/httpbind'
             *  to='vm-2k'
             *  wait='300'
             *  rid='782052'
             *  newkey='8e7d6cec12004e2bfcf7fc000310fda87bc8337c'
             *  ver='1.6'
             *  xmpp:xmlns='urn:xmpp:xbosh'
             *  xmpp:version='1.0'/>
             */

            body.Version        = BOSH_VERSION;
            body.XmppVersion    = "1.0";
            body.Hold           = m_Hold;
            body.Wait           = m_Wait;
            body.Rid            = rid;
            body.Polling        = 0;
            body.Requests       = m_Requests;
            body.To             = new Jid(m_XmppCon.Server);

            body.NewKey         = Keys[CurrentKeyIdx];

            body.SetAttribute("xmpp:xmlns", "urn:xmpp:xbosh");

            waitingRequests++;

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Address);

            WebRequestState state = new WebRequestState(req);
            state.Started           = DateTime.Now;
            state.Output            = body.ToString();
            state.IsSessionRequest  = true;

            req.Method          = METHOD;
            req.ContentType     = CONTENT_TYPE;
            req.Timeout         = m_Wait * 1000;
            req.KeepAlive       = m_KeepAlive;
            req.ContentLength   = state.Output.Length;

            try
            {
                IAsyncResult result = req.BeginGetRequestStream(new AsyncCallback(this.OnGetSessionRequestStream), state);
            }
            catch (Exception)
            {
            }
        }
        private void OnGetResponse(IAsyncResult ar)
        {
            try
            {
                // grab the custom state object
                WebRequestState state = (WebRequestState)ar.AsyncState;

                //Console.WriteLine(String.Format("OnGetResponse: id:{0}", state.WebRequestId.ToString()));

                //if (state.Aborted)
                //{
                //    waitingRequests--;
                //    if (waitingRequests == 0 && !terminated)
                //    {
                //        StartWebRequest();
                //    }
                //    return;
                //}


                HttpWebRequest request = (HttpWebRequest)state.WebRequest;


                HttpWebResponse resp = null;

                if (request.HaveResponse)
                {
                    // TODO, its crashing mostly here
                    // get the Response
                    try
                    {
                        resp = (HttpWebResponse)request.EndGetResponse(ar);
                    }
                    catch (WebException ex)
                    {
                        waitingRequests--;
                        if (ex.Response == null)
                        {
                            StartWebRequest();
                        }
                        else
                        {
                            HttpWebResponse res = ex.Response as HttpWebResponse;
                            if (res.StatusCode == HttpStatusCode.NotFound)
                            {
                                TerminateBoshSession();
                            }
                            //if (waitingRequests == 0)
                            //{
                            //    StartWebRequest();
                            //}
                        }
                        return;
                    }

                    // The server must always return a 200 response code,
                    // sending any session errors as specially-formatted identifiers.
                    if (resp.StatusCode != HttpStatusCode.OK)
                    {
                        waitingRequests--;
                        if (resp.StatusCode == HttpStatusCode.NotFound)
                        {
                            //Console.WriteLine("Not Found");
                            TerminateBoshSession();
                        }
                        //FireOnError(new PollSocketException("unexpected status code " + resp.StatusCode.ToString()));
                        return;
                    }
                }
                else
                {
                    //Console.WriteLine("No response");
                }

                Stream rs = resp.GetResponseStream();

                int          readlen;
                byte[]       readbuf = new byte[1024];
                MemoryStream ms      = new MemoryStream();
                while ((readlen = rs.Read(readbuf, 0, readbuf.Length)) > 0)
                {
                    ms.Write(readbuf, 0, readlen);
                }

                byte[] recv = ms.ToArray();

                if (recv.Length > 0)
                {
                    string sbody   = null;
                    string stanzas = null;

                    ParseResponse(Encoding.UTF8.GetString(recv, 0, recv.Length), ref sbody, ref stanzas);
                    //string res = Encoding.UTF8.GetString(recv, 0, recv.Length);

                    if (stanzas != null)
                    {
                        byte[] bStanzas = Encoding.UTF8.GetBytes(stanzas);
                        base.FireOnReceive(bStanzas, bStanzas.Length);
                    }
                    else
                    {
                        if (terminate && !terminated)
                        {
                            // empty teminate response
                            TerminateBoshSession();
                        }
                        //Console.WriteLine("Empty Response");
                    }
                }

                // cleanup webrequest resources
                ms.Close();
                rs.Close();
                resp.Close();

                waitingRequests--;

                if (waitingRequests == 0 && !terminated)
                {
                    StartWebRequest();
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine("Error in OnGetResponse");
                //Console.WriteLine(ex.Message);
            }
        }
        private void OnGetSessionRequestResponse(IAsyncResult result)
        {
            // grab the custom state object
            WebRequestState state   = (WebRequestState)result.AsyncState;
            HttpWebRequest  request = (HttpWebRequest)state.WebRequest;

            //state.TimeOutTimer.Dispose();

            // get the Response
            HttpWebResponse resp = (HttpWebResponse)request.EndGetResponse(result);

            // The server must always return a 200 response code,
            // sending any session errors as specially-formatted identifiers.
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                //FireOnError(new PollSocketException("unexpected status code " + resp.StatusCode.ToString()));
                return;
            }

            Stream rs = resp.GetResponseStream();

            int readlen;

            byte[]       readbuf = new byte[1024];
            MemoryStream ms      = new MemoryStream();

            while ((readlen = rs.Read(readbuf, 0, readbuf.Length)) > 0)
            {
                ms.Write(readbuf, 0, readlen);
            }

            byte[] recv = ms.ToArray();

            if (recv.Length > 0)
            {
                string body    = null;
                string stanzas = null;

                string res = Encoding.UTF8.GetString(recv, 0, recv.Length);

                ParseResponse(res, ref body, ref stanzas);

                Document doc = new Document();
                doc.LoadXml(body);
                Body boshBody = doc.RootElement as Body;

                sid        = boshBody.Sid;
                polling    = boshBody.Polling;
                m_MaxPause = boshBody.MaxPause;

                byte[] bin = Encoding.UTF8.GetBytes(DummyStreamHeader + stanzas);

                base.FireOnReceive(bin, bin.Length);

                // cleanup webrequest resources
                ms.Close();
                rs.Close();
                resp.Close();

                waitingRequests--;

                if (waitingRequests == 0)
                {
                    StartWebRequest();
                }
            }
        }
        public void RequestBoshSession()
        {
            /*
             * Example 1. Requesting a BOSH session
             *
             * POST /webclient HTTP/1.1
             * Host: httpcm.jabber.org
             * Accept-Encoding: gzip, deflate
             * Content-Type: text/xml; charset=utf-8
             * Content-Length: 104
             *
             * <body content='text/xml; charset=utf-8'
             *    hold='1'
             *    rid='1573741820'
             *    to='jabber.org'
             *    route='xmpp:jabber.org:9999'
             *    secure='true'
             *    ver='1.6'
             *    wait='60'
             *    ack='1'
             *    xml:lang='en'
             *    xmlns='http://jabber.org/protocol/httpbind'/>
             */

            lastSend = DateTime.Now;

            // Generate the keys
            GenerateKeys();
            rid = GenerateRid();
            Body body = new Body();

            /*
             * <body hold='1' xmlns='http://jabber.org/protocol/httpbind'
             *  to='vm-2k'
             *  wait='300'
             *  rid='782052'
             *  newkey='8e7d6cec12004e2bfcf7fc000310fda87bc8337c'
             *  ver='1.6'
             *  xmpp:xmlns='urn:xmpp:xbosh'
             *  xmpp:version='1.0'/>
             */

            body.Version     = BOSH_VERSION;
            body.XmppVersion = "1.0";
            body.Hold        = m_Hold;
            body.Wait        = m_Wait;
            body.Rid         = rid;
            body.Polling     = 0;
            body.Requests    = m_Requests;
            body.To          = new Jid(m_XmppCon.Server);

            body.NewKey = Keys[CurrentKeyIdx];

            body.SetAttribute("xmpp:xmlns", "urn:xmpp:xbosh");

            waitingRequests++;

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Address);

            WebRequestState state = new WebRequestState(req);

            state.Started          = DateTime.Now;
            state.Output           = body.ToString();
            state.IsSessionRequest = true;

            req.Method        = METHOD;
            req.ContentType   = CONTENT_TYPE;
            req.Timeout       = m_Wait * 1000;
            req.KeepAlive     = m_KeepAlive;
            req.ContentLength = state.Output.Length;

            try
            {
                IAsyncResult result = req.BeginGetRequestStream(new AsyncCallback(this.OnGetSessionRequestStream), state);
            }
            catch (Exception)
            {
            }
        }