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

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

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

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

If the timer expiresbefore a response packet has been forthcoming from the OBEX server, theTRequestStatus associated with the OBEX command will complete aspecific timeout error, KErrIrObexRespTimedOut, and the transportlink will be brought down.This method of detecting unresponsive OBEX servers is much betterthan setting an overall timeout for the entire operation as it is often difficultto predict how long a given command will take to complete, while arelatively short timeout can be applied to individual request–responseexchanges.

The value of the timeout should be set large enough that theOBEX server will have an opportunity to build the first response packet,but not so large that the user is left waiting too long for feedback – aroundfive seconds would be a good starting value.Retrieving the most recent response code from an OBEX serverDue to a historical anomaly in the mapping of OBEX response codes toSymbian error codes used by the CObexClient API, it is not alwayspossible to determine the exact response code that was returned ina response packet by an OBEX server following a request packet.This limitation is removed in Symbian OS v9.2 with the addition ofCObexServer::LastServerResponseCode().

The function returnsthe full, untranslated response code from the most recent response packetsent from the server. Use of this function must be restricted to when theOBEX client application is sure that a response packet has been returnedby the OBEX server, or a panic will result.10.3 SummaryIn this chapter we’ve seen:• OBEX is intended as a simple, compact protocol intended to serve asimilar purpose to HTTP on mobile or resource constrained devices342OBEX• it is a request-response based protocol operating between a client anda server.

It uses Headers encoded within OBEX packets to conveydata between the two• OBEX offers a convenient abstraction for transferring objects (oftenfiles) between devices• it can work over multiple different transports including Bluetooth andIrDA, offering potential for reuse of the same core OBEX applicationcode over more than one transport.11HTTP11.1 HTTP OverviewHTTP is a communication mechanism for transferring informationbetween devices, defined by the IETF.

Originally designed for transferring web pages, it has expanded beyond its original role into a generaltransport protocol between devices. This has been greatly helped by thefact that HTTP is allowed through many firewalls where other IP-basedprotocols are blocked.The version of HTTP now in use by most web servers is HTTP 1.1.HTTP uses a client-server model and runs at the level above TCP. Themost important standard, RFC2616, describes the makeup of messagessent between an HTTP client and an HTTP server.

The client sendsrequests to the server and receives responses.11.1.1 HTTP APIsSymbian OS provides an HTTP client stack known as the HTTP framework. This was first introduced in Symbian OS v7.0. This chapter describeshow to use the HTTP framework, starting with a simple Get commandand then looking at more powerful customization of the framework.

Allprotocol-defined request methods (including Get and Post) are supported.Applications using the framework don’t need to know about HTTPprotocol details, allowing them to concentrate on creating and processingcontent. The framework provides a set of APIs – this chapter illustrateshow you can use them.Users of the framework in Symbian OS include the Java HTTP implementation, SyncML, and the Online Certificate Status Protocol (OSCP).Example applications that might use the HTTP framework include webbrowsers or a download manager.344HTTPAn example application that allows uploading of images to the webbased photo sharing service Flickr, will be used to illustrate API usage.This provides a API – CFlickrRestAPI – which is used by the MTMexample in Chapter 9 to extend the SendAs service to allow uploading ofimages to Flickr,In addition to standard HTTP 1.1 services, the following functionalityis supported by the framework:• compatibility with HTTP 1.0 servers• authentication, both basic and digest (defined in RFC 2617)• secure connections (RFC 2818) – triggered by specifying https asthe URI scheme in the request URI.

The secure connection will bemade automatically.What is not supported:• no caching support is provided by default, although some UI platformsprovide filters that implement caching• cookie management• content encoding (or decoding). Again, some UI platforms may deliverfilters that implement content encoding and decoding.The architecture of the HTTP frameworkFigure 11.1 shows the high-level architecture of the HTTP framework,including the filters that can be used to extend or modify the framework’sbehaviour. We describe the client APIs first; then move on to the use ofthe supplied filters, as well as the various parameters that can be usedto configure a connection; then finally finish off by talking about how tocreate your own filters to load into the framework.We also discuss the use of the Stringpool by the HTTP framework.

TheStringpool is a mechanism for efficiently storing and comparing stringsby keeping one central copy of the string per thread, and allowing clientsto pass a compact representation of the string around (internally this isrepresented as an integer, but the classes for accessing strings hide thisdetail from the API user). Use of the Stringpool is particular beneficialfor protocols that use a lot of well-known and static text strings, such asHTTP.

Further details are given in section 11.8.11.2Getting Started: Creating a SessionAlthough HTTP is a stateless protocol, the framework supports the notionof a session, during which multiple HTTP transactions can take place.GETTING STARTED: CREATING A SESSION345Client applicationFiltersHTTPHTTP protocol handlerSecure socketsESOCKTCP/IPFigure 11.1High-level architecture of the HTTP frameworkFor example a web browser would use one session but is likely to havemultiple HTTP transactions, some of which may take place concurrently.First, we need to open a session using the session API –RHttpSession.

RHTTPSession has an overhead in both memoryuse and creation time, so typically you should only create one sessionin an application. Applications that wish to perform HTTP transactionsover multiple network connections should note, however, that eachHTTP session is bound to a single RConnection, so they need oneRHTTPSession per network connection they wish to use.Here are the most interesting methods on RHttpSession:class RHTTPSession{public:IMPORT_C void OpenL();IMPORT_C void OpenL(const TDesC8& aProtocol,MHTTPFilterCreationCallback* aSessionCallback);IMPORT_C void Close();IMPORT_C RHTTPTransaction OpenTransactionL(const TUriC8& aURI,MHTTPTransactionCallback& aCallback, RStringF aMethod = RStringF());IMPORT_C RStringPool StringPool() const;IMPORT_C RHTTPConnectionInfo ConnectionInfo() const;inline RHTTPFilterCollection FilterCollection() const;IMPORT_C RHTTPHeaders RequestSessionHeadersL();IMPORT_C RHTTPHeaders ResponseSessionHeadersL();};346HTTPWe create a session by calling OpenL().

Within the session a clientmakes requests to, and monitors responses from, different HTTP servers.Example 11.1 shows the session being configured for use with theexample Flickr upload service.void CFlickrRestAPI::ConstructL(){// Open RHTTPSession with default protocol ("HTTP/TCP")iSession.OpenL();// initialize handlesUser::LeaveIfError(iSocketServ.Connect());User::LeaveIfError(iConnection.Open(iSocketServ));// set them for use with open http session represented by iSessionRStringPool strP = iSession.StringPool();RHTTPConnectionInfo connInfo = iSession.ConnectionInfo();connInfo.SetPropertyL(strP.StringF(HTTP::EHttpSocketServ,RHTTPSession::GetTable()), THTTPHdrVal(iSocketServ.Handle()));TInt connPtr = reinterpret_cast<TInt>(&(iConnection));connInfo.SetPropertyL(strP.StringF(HTTP::EHttpSocketConnection,RHTTPSession::GetTable()), THTTPHdrVal(connPtr));// Setup the usual headers and indicate that the body will be multipartRHTTPHeaders httpHeader = iSession().RequestSessionHeadersL();SetHeaderL(httpHeader, HTTP::EUserAgent, KUserAgent);SetHeaderL(httpHeader, HTTP::EAccept, KAccept);SetHeaderL(httpHeader, HTTP::EContentType, KMultipartContentType());...}Example 11.1Creating a sessionIn Example 11.1 there are a few more details which need explaining:1.RequestSessionHeadersL() is used to get the session requestheaders.

These headers, once set, will be applied to all requests sentin the session.2.We are setting some session properties so the session will use ournetwork connection (iConnection).11.2.1 Session PropertiesThe framework has properties that can be used to modify the sessionconfiguration. These can be set by the client and will be applied to allactivities within a session.A particular property is set by calling CHttpConnectionInfo::SetProperty().

The existing value of a property can also be retrievedusing RHTTPPropertySet.CREATING AND SUBMITTING A TRANSACTION347The different property values, which alter the behavior of the frameworkin various ways, are defined in RHTTPConnectionInfo.h.By default the framework will create a network connection for you. Thiswill be owned by the framework and be created using the settings for thedefault access point in CommsDat.

This may, depending on the configuration, trigger a user prompt asking them to select a network connection.You can override this behavior by providing your own RConnection foruse by the session. Ownership of the connection remains with the client,so don’t forget to call RConnection::Close() once you have finished using the connection with the HTTP framework.

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

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

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

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