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

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

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

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

This base class actually offers two distinct ways tohandle non-body data.CObexBaseObjectCObexHeaderSet111*CObexHeaderCObexBufObjectCObexFileObjectFigure 10.4 Symbian OS OBEX object classes292OBEXOld-style APIThe original OBEX APIs offer a number of setter and getter function pairs,each pair being specific to a particular header, for example:void CObexBaseObject::SetNameL(const TDesC& aDesc);const TDesC& CObexBaseObject::Name();When SetNameL() is called, the object would be updated to adda Name header. The presence or absence of a particular header in anobject can be checked by using the ValidHeaders() function, whichreturns a TObexHeaderMask.

TObexHeaderMask is a bit field madeby using bitwise OR to combine values representing individual headertypes, such as KObexHdrName and KObexHdrType. These values aredefined in obexconstants.h.In normal use, ValidHeaders() is more useful when inspecting areceived object, as the same bits are set when a header of a particulartype is picked up during reception of an object.

It can be used to decideif it is worth using the corresponding getter function to extract a givenheader from the object. Upon object creation or reset, the valid headerbit field defaults to 0x0000, indicating that no headers are valid (i.e.,present in the object).Once an object has had all the appropriate headers set, an attempt totransfer that object using a Put or a Get command will normally send allthe valid headers.

The sending of any particular header can be suppressedby resetting (i.e., making equal to 0) the corresponding bit of the headermask. The header mask is another bit field using the same values definedin obexconstants.h, but in this case, the bit corresponding to aparticular header type is set to 0 if the header is not to be sent, or 1 if itshould be sent. This header mask bit field defaults to 0xFFFF, indicatingthat all the valid headers for the object should be sent. The applicationwriter may use the getter and setter function pair for the header maskto extract and modify this default value. (In practice, it is not clear howuseful this feature actually is!)The remaining peculiarity of the old-style API is the handling of HTTPheaders. HTTP headers are slightly unusual in that there can be morethan one in a given object.

This leads to slightly unusual semantics to theHTTP setter and getter functions:void CObexBaseObject::AddHttpL(const TDesC8& aDesc);const RPointerArray<HBufC8>* CObexBaseObject::Http() const;Please note the ‘add’ semantics of the setter function, and the arrayreturn value of the getter function. Unlike the other setter functions, theAddHttpL() function simply appends another HTTP header to the setbelonging to the object.OBEX IN SYMBIAN OS293New-style APIThe new-style API was introduced in Symbian OS v7.0s and has beenavailable since then.While the old-style API sufficed for a number of releases, it was notparticularly scalable. When support for user-defined header values wasintroduced into the OBEX implementation, it was necessary to rethink theheader handling in the API.

A more scalable and consistent means wasdevised to accommodate the setting and getting of headers.While the individual setter and getter pairs remained for backwardsource and binary compatibility, three new functions were added toCObexBaseObject to allow header manipulation:void CObexBaseObject::AddHeaderL(CObexHeader& aHeader);const CObexHeaderSet& CObexBaseObject::HeaderSet() const;CObexHeaderSet& CObexBaseObject::HeaderSet();These new functions model the representation of headers within theobject; each CObexBaseObject (or CObexBaseObject derived class)has a header set, made up of an arbitrary collection of headers. Twonew classes were introduced to directly represent these to the applicationwriter: CObexHeaderSet and CObexHeader.

Each CObexBaseObject owns a CObexHeaderSet, which in turn will own zero ormore CObexHeader objects. The functions listed above operate onthe CObexHeaderSet owned by the CObexBaseObject and allowthe set to be added to and accessed in a const form and non-constform, respectively.For an object created for transfer to another device, the CObexHeaderSet belonging to the CObexBaseObject defines the set of headersthat will be sent during a transfer (except Body and End-of-Body headers).For a received object, the CObexHeaderSet defines the set of headers received during the transfer. The CObexHeaderSet can be iteratedthrough using an MObexHeaderCheck-derived class (of which morelater).CObexHeader, CObexHeaderSet and MObexHeaderCheckThe application writer should note a couple of things about theseclasses.

Firstly, they are both Symbian C–style classes, meaning thatthey are derived from the CBase class and intended for use solely on theheap.Secondly, an instance of CObexHeader is actually a handle to an‘underlying’ header representation, as shown in Figure 10.5. This allowsmultiple CObexHeader instances to share a single underlying header294OBEXrepresentation, thereby saving RAM (and potentially a lot of RAM, depending on how big the header representation is, and how many copies of itare required within an application). The application writer needs to beaware of the implications of this.Name header == "Fred"myHeader : CObexHeaderheaderValue : ObexUnderlyingHeaderName header == "Fred"(reference count == 1)Figure 10.5 CObexHeader internal representationWhen a copy of one instance of CObexHeader is created using theCObexHeader::CopyL() function, the new copy will share the sameunderlying header representation, that is, it is a shallow copy, as shownin Figure 10.6.Also, when one instance of CObexHeader is set to the value of anotherinstance of CObexHeader using the CObexHeader::Set() function,both instances will share the same underlying header representation.Most of the time, this sharing of underlying headers is transparentto the application writer; a reference count of the number of CObexHeader instances referencing the underlying header representation iskept automatically.

An underlying header will only be deleted when thelast CObexHeader referencing is deleted.Name header == "Fred"Name header == "Fred"myHeader : CObexHeaderCObex::CopyL()myHeaderCopy : CObexHeaderheaderValue : ObexUnderlyingHeaderName header == "Fred"(reference count == 2)Figure 10.6CObexHeaders with shared internal representationOBEX IN SYMBIAN OS(1) Set Name header = "Bob"myHeader : CObexHeader295(3) Name header == "Bob"myHeaderCopy : CObexHeaderheaderValue : ObexUnderlyingHeader(2) Name header value changesfrom "Fred" to "Bob"(reference count == 2)Figure 10.7 Consequence of shared internal representationApplication writers need to be particularly aware of the sharing ofunderlying headers when the header value is changed.

In this case, allCObexHeader instances that reference the changed underlying headerwill effectively have their values updated, as shown in Figure 10.7.Using CObexHeader If you haven’t already, now is a good time to takea look at obexheaders.h to get a feel for CObexHeader.

Its mainfeatures are a static factory function (NewL) used to create a new instance,a group of setter functions corresponding to each of the four encodingtypes, and a group of getter functions again corresponding to each of thefour encoding types. There is also a function (Type()) which can beused to determine which encoding type has been used for a given header.Below is an example of setting and inspecting a CObexHeader.// Some constant definitionsconst TUint8 KTypeHeaderHi = 0x42;_LIT8(KFolderListingType, "x-obex/folder-listing\x00");_LIT(KOutputFormat, "Byte Sequence Value = %S")_LIT(KFolderListingOutput, "Type header, value == folder listing\n");// Create new instance of CObexHeader on the heapCObexHeader* header = CObexHeader::NewL();// Has no value yetCleanupStack::PushL(header);// Place on cleanup stackheader->SetByteSeqL(KTypeHeaderHi,KFolderListingType);// Set valueCleanupStack::Pop(header);// Remove from cleanup stack//{Intervening code that might change value of header}// Check that value of header is still the same...//if ( header->HI() == KTypeHeaderHi &&header->AsByteSeq() == KFolderListingType )296OBEX{//Value of header is unchanged}delete header;// destroy headerExample 10.1Use of CObexHeaderExample 10.1 shows the creation of a CObexHeader instance.

Initially, the CObexHeader has no value. The value is then set usingSetByteSeqL().There are two things of interest here; firstly, we use SetByteSeqL()since the HI indicates a byte sequence encoding (HI == 0x42, so two highorder bits == 01 in binary). Also note that because SetByteSeqL() hasto allocate memory to store a copy of the folder listing type string it is aleaving function, denoted by the trailing ‘L’ in the function name. This isthe reason that the header is placed on the cleanup stack before beingset. In this respect, SetByteSeqL() is similar to SetUnicodeL(), butdissimilar to SetByte() and SetFourByte() which do not allocateany memory and therefore do not leave.The next part of the code illustrates how a header can be inspected.The HI of the header is checked first.

This effectively checks two things.Firstly, it ensures that the right header has been found (e.g., the Typeheader rather than the Name header). Secondly, because the encodingtype is held as part of the HI, it ensures that the header is using the correctencoding type. This is an important step, since attempting to extract theheader value using an inappropriate getter function will result in a panic.Once it is established that the HI is correct, AsByteSeq() is used toextract the value of the header so that a comparison can be made withthe required value. The header is then finally deleted. Unless anotherCObexHeader has been created which references the same underlyingheader value, this underlying header value will also be deleted.Using CObexHeaderSet Setting and inspecting individual headers isuseful, but most often headers are dealt with in groups.

CObexHeaderSet was created as a container class for groups of headers.Its main features are a static factory function (NewL()) to create a newinstance of CObexHeaderSet, a means to add and delete headers, ameans to find specific headers, and finally a means to iterate throughthe headers in the collection. As a result of the iteration feature, eachCObexHeaderSet has a concept of the ‘current element’, which can bereset to the first element of the set, or moved on to the next element.Below is an example of how to use some of these features.// Start with some constant definitions//const TUint8 KNameHeaderHi = 0x01;OBEX IN SYMBIAN OS297const TUint8 KLengthHeaderHi = 0xC3;const TUint8 KUserDefinedHi = 0x70;_LIT(KObjectName, "This is the name of the object");const TInt KObjectLength = 400;_LIT8(KUserDefinedByteSeqValue, "This could be anything, but must be zeroterminated\x00");// Create header set//CObexHeaderSet* headerSet = CObexHeaderSet::NewL();CleanupStack::PushL(headerSet);// Create and add first header//CObexHeader* header1 = CObexHeader::NewL();CleanupStack::PushL(header1);header1->SetUnicodeL(KNameHeaderHi, KObjectName);// Set valueUser::LeaveIfError(headerSet->AddHeader(header1));CleanupStack::Pop(header1);// Ownership has been passed to// CObexHeaderSet// Create and add second header//CObexHeader* header2 = CObexHeader::NewL();header2->SetFourByte(KLengthHeaderHi, KObjectLength); // Set valueCleanupStack::PushL(header2);User::LeaveIfError(headerSet->AddHeader(header2));CleanupStack::Pop(header2);// Ownership has been passed to// CObexHeaderSet// Create and add third header//CObexHeader* header3 = CObexHeader::NewL();CleanupStack::PushL(header3);header3->SetByteSeqL(KUserDefinedHi, KUserDefinedByteSeqValue);User::LeaveIfError(headerSet->AddHeader(header3));CleanupStack::Pop(header3);//Ownership has been passed to// CObexHeaderSetExample 10.2Creating and populating a CObexHeaderSetExample 10.2 shows the creation and population of a CObexHeaderSet object.

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

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

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

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