Главная » Просмотр файлов » Symbian OS Communications

Symbian OS Communications (779884), страница 72

Файл №779884 Symbian OS Communications (Symbian Books) 72 страницаSymbian OS Communications (779884) страница 722018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 72)

In the case of HTTP there are a great many strings being used in asession, including the header field names.Stringpool handles 8-bit strings, either case sensitive and accessedvia RString; or case insensitive, accessed via RStringF. When asession is opened, it creates a stringpool accessible for the lifetime of thesession. All commonly used HTTP strings are loaded into the session’sstringpool from a static string table. The RStringPool API offers theability to dynamically load new strings and string tables into the stringtable maintained by the HTTP session. It also offers the ability to translatebetween the RStingTokenF returned from some HTTP APIs and theRStingF class.class RStringPool{public:IMPORT_C void OpenL();IMPORT_C void OpenL(const TStringTable& aTable);354HTTPIMPORT_C void OpenL(const TStringTable& aTable,MStringPoolCloseCallBack& aCallBack);IMPORT_C void Close();IMPORT_C RStringF OpenFStringL(const TDesC8& aString) const;IMPORT_C RString OpenStringL(const TDesC8& aString) const;IMPORT_C RString String(RStringToken aString) const;IMPORT_C RString String(TInt aIndex,const TStringTable& aTable) const;IMPORT_C RStringF StringF(RStringTokenF aString) const;IMPORT_C RStringF StringF(TInt aIndex,const TStringTable& aTable) const;};RString and RStringF are the classes that act as handles to specificstrings:class RString : public RStringBase{public:inline RString Copy();inline operator RStringToken() const;inline TBool operator==(const RString& aVal) const;inline TBool operator!=(const RString& aVal) const;};class RStringF : public RStringBase{public:inline RStringF Copy();inline operator RStringTokenF() const;inline TBool operator==(const RStringF& aVal) const;inline TBool operator!=(const RStringF& aVal) const;};The major use of the string table in HTTP is to open pre-defined stringsfrom the HTTP protocol to pass them to HTTP APIs.

This can be seen inexample 11.2 where RStringPool is used to access the HTTP::EPOSTstring.All header field names and values are stored as case-insensitive strings.The one exception is cookie values. These are stored as case-sensitivestrings.There are some API oddities that you should be aware of when usingStringpool, where sometimes the APIs do not operate in the standardSymbian manner. Specifically, when creating strings using OpenFStringL(), you need to ensure the object is closed when you havefinished with it, as you would expect. For strings already in the stringtable,StringF() is used; in this case you should not close the string.void CFlickrRestAPI::SetHeaderL(RHTTPHeaders aHeaders, TInt aHdrField,const TDesC8& aHdrValue ){RStringF valStr = iSession.StringPool().OpenFStringL(aHdrValue);RStringF nameStr = iSession.StringPool().StringF(aHdrField,RHTTPSession::GetTable())PROXY SUPPORT355CleanupClosePushL(valStr);THTTPHdrVal val(valStr);aHeaders.SetFieldL(nameStr, val);CleanupStack::PopAndDestroy(&valStr);}Example 11.4stringsUsing Stringpool to access both static and dynamicFor example, as shown in Example 11.4, when setting a header field,the header field name would be opened using StringF(), the valueusing OpenFString() (unless the value happens to be a commonlyused string that is available as a static string, in which case it would alsobe opened using StringF()).11.9 Proxy SupportSupport for setting proxy information is provided at the session level andon a per transaction basis through the use of HTTP properties.

Whenset at the RHTTPSession level, the proxy information is used for everytransaction, except if overridden by the transaction itself.TStringTable& stringTable = RHTTPSession::GetTable();RHttpTransaction trans = iSession.OpenTransactionL(...);RHTTPTransactionPropertySet transInfo = aTransaction.PropertySet();transInfo.SetPropertyL(iSession.StringPool().StringF(HTTP::EProxyUsage, stringTable),iSession.StringPool().StringF(HTTP::EUseProxy, stringTable));// proxyAddressStr = buffer containing value of proxy addressRStringF proxyAddress =iSession.StringPool().OpenFStringL(proxyAddressStr);CleanupClosePushL(proxyAddress);transInfo.SetPropertyL(iSess.StringPool().StringF(HTTP::EProxyAddress,stringTable, proxyAddress);CleanupStack::PopAndDestroy(&proxyAddress);Example 11.5Setting a proxyThe property EProxyUsage is set to indicate a proxy should be used,the address being specified in the property, EProxyAddress.

This shouldinclude the port number if it differs from the default (8080). Example 11.5shows how to set proxy information for a specific transaction.General HTTP proxy information is available in CommsDat for eachIAP, if that IAP has a proxy set; however, if an application wishes or needsto use its own proxy then it can supply the correct information directly tothe framework.35611.10HTTPCookie HandlingCookie support is not provided by the framework. Cookies are handledlike any other header field, although there are some differences.

Cookiefield values are stored and accessed as case-sensitive strings in thestringpool. As the SetCookie header can appear multiple times, and theformat of a cookie header differs from most other header fields, accessingthe data (via GetField() and GetParam()) is slightly different.TInt cookieCount = headers.FieldPartsL(setCookie);THTTPHdrVal name, value;RStringF setCookie =strP.StringF(HTTP::ESetCookie,RHTTPSession::GetTable());RStringF cookieName = strP.StringF(HTTP::ECookieName,RHTTPSession::GetTable());RStringF cookieValue= strP.StringF(HTTP::ECookieValue,RHTTPSession::GetTable());// May be a number of set-cookie header fields present in header of aresponse.TInt ii=cookieCount;while (--ii){aHeaders.GetParam(setCookie, cookieName , name, ii);aHeaders.GetParam(setCookie, cookieValue, value, ii);// Parameters obtained explicitly.

Other possible parameters are:EDomain,// EMaxAge, ECookiePort, EComment, ECommentURL, ESecure, EDiscard,EVersion,RStringF cookieExpires = strP.StringF(HTTP::EExpires,RHTTPSession::GetTable());if (aHeaders.GetParam(aFieldName, cookieExpires, hdrVal, aPartIndex) ==KErrNone)// store string cookieExpires.DesC()}Example 11.611.11Cookie handling exampleHTTP Connection ConfigurationIt is possible to configure the session in order to potentially enhance performance of the framework for a particular application.

The session propertiescan be modified based on the usage patterns that an application exhibits.11.11.1 Pipelining and Persistent ConnectionsPipelining and persistent connections are defined as part of the HTTP/1.1standard. Persistent connections allow multiple transactions to a serverHTTP CONNECTION CONFIGURATION357to be sent over a single socket connection. Pipelining allows one ormore new transactions to be submitted to a server over a persistentconnection before a previous transaction has completed.

The HTTPframework supports both pipelining and persistent connections.An HTTP client may submit multiple requests to the framework. Witha persistent connection (the default in HTTP/1.1), but without pipelining,an HTTP clients can submit multiple transactions in all cases. They arejust not queued on the connection. Only one transaction can be active foreach socket connection. Multiple connections will be used for requests todifferent hosts.With pipelining switched on, multiple transactions to the same hostcan be sent down one socket without waiting for a previous transaction tocomplete.

Obviously pipelining requires persistent connections in orderto operate. Figure 11.2 shows the difference in the request-responsepattern for the three types of connection – non-persistent connections,persistent connections without pipelining, and persistent connectionswith pipelining.When using network connections with high latency, such as GPRS, thebenefits of persistent connections and pipelining become clear – in thecase of persistent connections there is no need to pay the cost of settingup and tearing down a TCP connection for each transaction; and in thecase of pipelining, there is no need to wait for a server to respond to aprevious transaction before sending the next one. For typical web pages,which might consist of a number of small images loaded from the sameserver, the benefits can be substantial.LocalRemoteLocalRemoteLocalRemoteCreate new TCP connectionCreate new TCP connection(i)Figure 11.2pipelining(ii)(iii)Changes to request-response pattern when using persistent connections and358HTTPAs an example, let’s do some rough calculations based on networkmeasurements taken in the UK.

Характеристики

Тип файла
PDF-файл
Размер
3,18 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6353
Авторов
на СтудИзбе
311
Средний доход
с одного платного файла
Обучение Подробнее