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

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

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

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

This is a 100 % guaranteed way to terminally hang the thread in which the CObexClientis running! The usual way to handle such completions is to have anactive object await completion of the request, and to take appropriateaction in its RunL() function.This parallelism does not extend to other OBEX commands though;each instance of CObexClient may have only one OBEX commandrequest in progress at one time.8 An attempt by an OBEX client applicationto initiate another OBEX command when one is already in progresswill result in the new OBEX command completing immediately withKErrAccessDenied.An OBEX client application instantiates its CObexClient using theCObexClient::NewL() factory function.

At the time of creation, theapplication must have made choices on the transport over which OBEXshould run, and (maybe) the intended target device and service.Creation of CObexClient and selection of transportThere are actually two overloads of CObexClient::NewL() in SymbianOS v9.1, and three in v9.2.The original version takes a reference to a TObexProtocolInfostructure. This is a base class that does nothing more than identifythe transport type to be used (IrDA or Bluetooth), and is not of anyuse by itself.

It does, however, have a number of subclasses that definetransport specific details for each transport type, and it is instances of these7In fact, an application writer does have other options if they want to simply send anobject from one device to another – this is covered in Chapter 9, with the description of theSendAs API.

Some of the transports offered through the SendAs API use OBEX themselves,but hide all of the details away from the API user.8Abort is an exception to this rule as it can be called while OBEX commands areongoing. This is because Abort is used to bring ongoing OBEX commands to an end, andso has to be available at all times.306OBEXsubclasses that are passed into CObexClient::NewL() by applicationsusing OBEX.Before introducing the subclasses of TObexProtocolInfo, it isworth considering the characteristics of the transport types and protocols,to understand the differences in the way the transport is set up.OBEX client connections over IrDAFor OBEX client applications running over the IrDA infrared protocols,transport set up is trivial; the client application has no need to explicitly identify a specific device to be communicated with, because theline-of-sight characteristic of infrared means that the user can intuitively‘point and shoot’ at the device on which the required OBEX server isrunning9 .

Additionally, service discovery on IrDA is relatively straightforward – given a class and service name, it is possible to use the IrDAInformation Access Service (IAS) to determine the appropriate Tiny TP(another IrDA protocol) port number to connect to in order to access thatservice.10As a result, an OBEX client application running over IrDA need onlyidentify the class and name of the required service. When the clientapplication later initiates an OBEX Connect, CObexClient will makean IrDA connection to the device in line of sight, and performs IAS queriesto locate the required service on that device.The subclass of TObexProtocolInfo used to hold IrDA transport information is TObexIrProtocolInfo. TObexIrProtocolInfoadds a number of new fields to the iTransport field it inherits fromTObexProtocolInfo.When a TObexIrProtocolInfo object is created, its iTransportmember must be set to the value of the literal constant KObexIrTTPProtocol.

This allows CObexClient to correctly interpret the restof the fields in the class. (Where the optional iDiscoverySlots andiDiscoveryAttempts fields are set, iTransport must be set to thevalue of the constant KObexIrTTPProtocolV2). The values of theseconstants are defined in obexconstants.h.The first IrDA specific field in TObexIrProtocolInfo is a TIrdaSockAddr (socket address) field. The TIrdaSockAddr class isdefined by the infrared subsystem, and is itself made up a group offields that combine to describe the two ends of an IrDA connection. Thisfield is actually unused when creating a CObexClient.The most important fields of TObexIrProtocolInfo for an OBEXClient are iClassName and iAttributeName. These descriptor-based9Actually, IrDA is capable of more sophisticated point to multipoint modes of operation,but OBEX over IrDA is normally used as part of a point-and-shoot operation.

Hence, whenrequested to connect over IrDA while in range of a number of suitable IrDA devices, theSymbian OBEX client will attempt to connect to the first one it successfully discovers.10As stated earlier, more details of IrDA-specific details can be found in Chapter 5.OBEX IN SYMBIAN OS307fields are used to indicate the service to which the OBEX client wishes toconnect.TObexIrProtocolInfo info;_LIT8(KObexClass, "OBEX");_LIT8(KTinyTpLsapSel, "IrDA:TinyTP:LsapSel");info.iTransport = KObexIrTTPProtocol;info.iClassName = KObexClass;info.iAttributeName = KTinyTpLsapSel;iClient = CObexClient::NewL (info);Example 10.7Creating a CObexClient to run over IrDAThe remaining fields of TObexIrProtocolInfo are iDiscoverySlots and iDiscoveryAttempts, and are optional.

These fieldsare used to modify the way in which the IrDA transport link is established.Note how the iTransport member in the following example is set toKObexIrTTPProtocolV2 rather than KObexIrTTPProtocol. Thisdistinction is used by OBEX to determine whether to access and use thevalue in iDiscoverySlots and iDiscoveryAttempts, or whetherto use the default values for these two settings.TObexIrProtocolInfo info;_LIT8(KObexClass, "OBEX");_LIT8(KTinyTpLsapSel, "IrDA:TinyTP:LsapSel");info.iTransport = KObexIrTTPProtocolV2;info.iClassName = KObexClass;info.iAttributeName = KTinyTpLsapSel;info.iDiscoverySlots = KNumberOfDiscoverySlots;info.iDiscoveryAttempts = KNumberOfDiscoveryAttempts;iClient = CObexClient::NewL(info);Example 10.8 Creating a CObexClient to run over IrDA withmodified IrDA connection behaviourOBEX client connections over BluetoothFor Bluetooth, the task is somewhat more involved. Bluetooth has noconcept of line of sight so other means must be used to identify thedevice to which we are going to connect.

For this reason, an OBEX clientapplication must provide a Bluetooth device address to CObexClient toidentify the device on which the required service is running. The normalmeans of identifying such a device in the first place is to use the devicediscovery procedures covered in Chapter 4.Furthermore, the Bluetooth Service Discovery Protocol (SDP) is rathermore complex than IAS, and in addition to basic information such as portnumbers, a service record in the SDP database may contain information308OBEXwhich a client application needs to be aware of.

For example, in theBluetooth Object Push Profile (OPP), part of the SDP record is allocatedto specifying the formats of objects that the OBEX server applicationimplementing OPP can understand. This is definitely application, ratherthan OBEX, specific detail.For this reason, interrogating the SDP database on a target device is leftto the OBEX client application, and is beyond the scope of this chapter.SDP is covered in more detail in Chapter 4.As a result of this, a client application using OBEX over Bluetoothmust provide both a Bluetooth device address and a port number(specifically, an RFCOMM server channel number). The subclass ofTObexProtocolInfo used to hold this information is TObexBluetoothProtocolInfo.Maximum OBEX packet sizesThe second overload of CObexClient::NewL() also takes a referenceto a (subclass of) TObexProtocolInfo object as a parameter, but additionally takes a reference to an object of class TObexProtocolPolicy.This class allows finer control over the maximum packet size used byOBEX, which in turn allows tuning of the performance of OBEX transfers.The TObexProtocolPolicy offers two main functions, SetReceiveMtu() 11 and SetTransmitMtu().

These functions can beused to specify the size of buffer that is created by CObexClient toaccommodate incoming packets (SetReceiveMtu()), and outgoingpackets (SetTransmitMtu()).In practice, there is no guarantee that the full size of the allocatedbuffers will be used in an OBEX transfer. This depends on the capabilitiesof the other device. The receiving capabilities of an OBEX client andserver are determined during connection establishment, each side tellingthe other of the largest incoming packet it can accommodate.

If thereceiver can only accommodate packets smaller than those a sender iscapable of sending, the sender ‘throttles back’ the size of the packets itsends so that they do not exceed the receiving buffer size of the receivingdevice.It should be noted that this API offers the ability to independently setthe receive MTU and the transmit MTU: this is useful where a givenapplication of OBEX involves transfers predominantly in one direction.For example, where a given application involves an OBEX client sendinglarge amounts of data to an OBEX server, the OBEX client’s transmit MTUmight be increased to the maximum allowable, while the receive MTUmight be left at the default value, or even reduced below that default.11MTU = maximum transfer unit, a general term use to describe the size of the largestpacket of data that may be exchanged by a given layer of a communications protocol.OBEX IN SYMBIAN OS309Manipulating maximum OBEX packet sizes for improved performanceWe will diverge from discussion of the OBEX client API for a moment toconsider performance tuning and how this relates to OBEX packet size.The default packet size used for OBEX in Symbian OS is 4000 bytesper packet (reflecting the original use of OBEX as a means to beamsmall objects like vCards around).

The maximum allowable size for anOBEX packet as defined in the specification is 216 (65,536) bytes. Thereis therefore quite some scope for increasing the maximum packet size.Generally, the larger the size of an OBEX packet, the better theperformance of the transfer. This is partly because the ratio of OBEXpacket header information to OBEX packet payload is lower with a largepacket. Mainly though, it is because more payload per packet meansfewer packets are required to move an object of a given size, thusreducing the number of times that the processing overhead associatedwith receiving a packet is incurred. (Very generally, this overhead involvesparsing the incoming packet, constructing and sending another packet inresponse, and then waiting for another packet.) This is particularly truewith a conversational protocol like OBEX, where every packet sent froma client must be acknowledged before the next packet can be sent.

Thiscan be contrasted with Bluetooth’s RFCOMM with its credit-based flowcontrol, or TCP/IP’s ‘sliding window’ flow control mechanism.This ‘bigger is better’ maxim does not always hold true, however.When sending data, allocating a large maximum packet size is no useif the object to be transferred is smaller than the packet (where some ofthe allocated packet buffer space is unused), or if the receiving deviceis unable to handle packets that large.

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

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

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

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