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

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

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

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

The Disconnect()function can be used to do this. It takes a TRequestStatus& parameterwhich is used to indicate completion of a successful or unsuccessfuldisconnection. If the disconnection is successful, the TRequestStatuswill be completed with the value KErrNone.If a disconnection is unsuccessful, the TRequestStatus will becompleted with a value reflecting the response code from the server, andthe transport connection and OBEX session will both remain connected. Infact, there is only one valid situation defined in OBEX specification wherea disconnection is allowed to fail, and the Symbian OBEX implementationshould preclude this from happening.If such a problem should arise, it may be necessary to take moredrastic action to shut down the transport connection and OBEX session.See ‘Immediate shutdown of CObexClient’.OBEX IN SYMBIAN OS315void CMyObexClientApp::Disconnect(){// iClient is an initialised member variable of type CObexClient*iClient->Disconnect(iStatus);SetActive();////}Successful or unsuccessful completion of Disconnect command willresult in RunL() of this object being called.Example 10.14Use of DisconnectImmediate shutdown of CObexClientIn some circumstances, it may be necessary to immediately shut downthe OBEX client and halt any ongoing activities.

This may happen as theresult of an error condition in the OBEX application, or as the result ofthe OBEX client application being required to shut down by the wideroperating system, for example, when the phone is switched off.This immediate shutdown can be achieved simply by deleting theCObexClient object. The ongoing transport connection, and with it theongoing OBEX session, will be immediately disconnected.Application writers should remember that they retain ownership ofobjects passed into CObexClient’s Connect(), Put() and Get()functions, and remain responsible for deleting them.GetPutFinalResponseHeadersSome OBEX applications12 require that the final response packet fromthe OBEX server should contain status information in addition to theresponse code, in the form of OBEX headers. When an OBEX clientapplication is anticipating such headers at the end of a Put exchange,GetPutFinalResponseHeaders() can be used to access headerssent in the final Put response packet.The function returns a const CObexHeaderSet& which can beinspected in the usual way using CObexHeaderSet::Find() or theMObexHeaderCheck class.

Ownership of the header set remains withthe CObexClient.OBEX command completion and error codesWhen local errors (e.g., ‘Out of memory’) cause the completion of arequest, the request will be completed with a standard Symbian systemwide error code.When a particular command completes due to a successful (e.g.,‘Success’) or unsuccessful (e.g., ‘Unauthorized’) response from the remote12Notably, the Bluetooth Basic Imaging Profile (BIP).316OBEXOBEX server, it can be useful for the client application to know preciselywhat the response code was.The Symbian OS OBEX implementation uses a mapping to transformthe response code that completes a given OBEX command to producea Symbian-style error code (i.e., a TInt value of zero (KErrNone) orsmaller).

For historical reasons, some of the response codes are mapped topre-existing Symbian system-wide error codes, while others are mappedindividually to OBEX specific Symbian error codes, as illustrated inTable 10.5).The other OBEX response codes are mapped one to one to a range ofSymbian OBEX-specific error codes from KErrIrObexRespSuccessto KErrIrObexRespDatabaseLocked.Note: the mapping of several OBEX response codes to a single Symbian error code may be restrictive in some cases where the OBEXclient application requires the exact response code.

In Symbian OSv9.2, LastServerResponseCode() will allow the OBEX clientapplication to discover this response code following completion of anOBEX command. See section 10.2.10 for other additions in SymbianOS v9.2.10.2.6 OBEX Server APIThe OBEX server API in Symbian OS is defined by the classes CObexServer and MObexServerNotify. An object of class CObexServermust be instantiated by the OBEX server application, and the MObexServerNotify interface class must be inherited from and implemented by the OBEX server application. The class that implementsMObexServerNotify is very important as it responds to incomingevents from remote OBEX clients, and so defines the behaviour of theOBEX service.An OBEX server application instantiates its CObexServer using theCObexServer::NewL() factory function.

At the time of creation, theapplication must have made choices on the transport over which OBEXshould run, and (maybe) decisions about how the service should beadvertised and how remote OBEX clients should access it.Creation of CObexServer and selection of transportAs with CObexClient, there are two overloads of CObexServer::NewL() in Symbian OS v9.1 and three in v9.2. The v9.1 versionstake as parameters the same TObexProtocolPolicy and TObexProtocolInfo derived structures as CObexClient::NewL(). ForCObexServer::NewL(), however, the TObexProtocolInfo derivedstructures are used slightly differently because in this case we are settingup a passive connection.OBEX IN SYMBIAN OS317Table 10.5 OBEX response codes mapping to standard Symbian error codesOBEX response codeSymbian error codeContinueSuccessCreatedAcceptedKErrNoneBad RequestUnauthorizedForbiddenNot AcceptableMethod Not AllowedKErrArgumentNot FoundKErrNotFoundTimed OutKErrTimedOutConflictKErrInUseNot ImplementedKErrNotSupportedPassive connections are a means to wait for some other entity (inthis case a remote OBEX client) to initiate a connection.

Once the otherentity has initiated the connection, the passive connection spawns a ‘live’connection over which the two entities can communicate.At this point, it is worth considering the characteristics of the transporttypes and protocols to understand the differences in the way the transportis set up to provide a passive connection.OBEX server connections over IrDA Transport set up is trivial forOBEX server applications running over IrDA, as CObexServer takescare of registering the IAS service advertisement and (by the use of theKAutoBindLSAP constant) selecting the TinyTP LSAP over which theOBEX server will run.

This is illustrated in example code below._LIT8(KClassName, "OBEX");_LIT8(KAttributeName, "IrDA:TinyTP:LsapSel");TObexIrProtocolInfo aInfo;info.iAddr.SetPort(KAutoBindLSAP);info.iTransport = KObexIrTTPProtocol;info.iClassName = KClassName;aInfo.iAttributeName = KAttributeName;iServer= CObexServer::NewL (aInfo);Example 10.15informationSetting up OBEX server with IrDA transport318OBEXIt should be noted that on return from NewL(), the transport haslargely been prepared to accept incoming connections, but will not doso until Start() is called to activate the OBEX server (for IrDA, it is notuntil Start() is called that the IAS record is registered).

See below formore information on Start().OBEX server connections over Bluetooth Transport set up for Bluetoothis somewhat more involved than for IrDA. Provided with an RFCOMMserver channel number, CObexServer will create the passive Bluetoothconnection, and wait for connection when subsequently told to Start().However, this is not enough to allow remote devices to use the service.There are a number of other things that a Bluetooth server applicationmust consider, specifically:• Setting the major service class correctly in the class of device (CoD)• Registering an SDP record• Setting link security• Device discoverability.All of these topics are covered at greater length in Chapter 4.

AnOBEX-centric summary is included here for convenience.Class of device – In Bluetooth, the class of device is a three-byte bitarray that is returned from a device that is responding to an inquiryscan. Its purpose is to provide a quick, high-level view of what kind ofdevice is responding to the inquiry (e.g., computer, phone) and whattypes of service the device supports. One of these service types is ‘ObjectTransfer’, and the bit corresponding to this service type should be setby the OBEX server application while the device is offering OBEX-basedservices over Bluetooth – however, see the discussion in Chapter 4 aboutpossible problems with setting or unsetting this bit.From v9.2, OBEX will set this bit appropriately when it starts up, sothere is no need for the application to do anything about it (obviouslythe application still needs to register an SDP record though).SDP – Each Bluetooth service passively waiting for a connection fromsome remote Bluetooth device must advertise itself in the SDP databaseso that remote Bluetooth devices can determine firstly that the serviceis supported and secondly how to connect to it.

Specifically for OBEXservices, this means over which RFCOMM server channel it runs.CObexServer does not do SDP registration on behalf of an OBEXserver application. This is for the same reason that the OBEX client doesOBEX IN SYMBIAN OS319not perform SDP searches on behalf of the OBEX client application; inaddition to basic information such as server channel numbers, a Bluetoothservice record in the SDP database may need to contain information thatonly an OBEX server application will be able to provide. Therefore, theOBEX server application is responsible for setting up its own SDP record,and tearing it down later when the service is closed down.

See Chapter 4for more details on how service records can be added and removed fromthe local service discovery database.Link security – Security options which need to be applied to the Bluetooth link must be set in the TObexBluetoothProtocolInfo. EachBluetooth link may optionally be authenticated, and when authenticated, optionally encrypted. It may also be marked as requiring explicitauthorization from the user.A description of the mechanisms involved is beyond the scope of thischapter, but the means to apply these link security options when OBEXruns over Bluetooth is straightforward.// NB.

iProtocolInfo is a TObexBluetoothProtocolInfoTBTServiceSecurity btServiceSecurity;btServiceSecurity.SetAuthentication(EFalse);btServiceSecurity.SetAuthorisation(ETrue);btServiceSecurity.SetEncryption(EFalse);iProtocolInfo.iAddr.SetSecurity(btServiceSecurity);Example 10.16Setting Bluetooth link security in OBEXThe values shown above would instate a low level of security fora service, specifically requiring the user to authorize a connectionmade to that service. This could be sufficient for a simple application used to beam a low-value object from one device to another in aone-off link operation (e.g., beaming a photograph from one phone toanother).Most services would require a higher level of security, requiringauthentication to ensure the correct devices are connected together, and(normally when using an authenticated link) encryption to ensure thatthe data being transferred is not accessible to other devices able to ‘listenin’ on the Bluetooth radio link.

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

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

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

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