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

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

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

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

As with PutPacketIndication(), it provides a means to track progress, and a means to respond toa Get request packet, and so brings the Get command to a premature halt.All the same considerations as with PutPacketIndication()apply to GetPacketIndication(), including the advisability of keeping the implementation lightweight and fast so as not to impair transferperformance.GetCompleteIndication Just before the final response packet issent to the OBEX client, CObexServer calls GetCompleteIndication() on the same MObexServerNotify-derived object. This330OBEXprovides the OBEX server application with a final chance to return anerror response code for the Get command.

Since the burden of inspecting,processing or storing the object is on the OBEX client in this case, usuallythe implementation of this function simply returns KErrNone.Handling SetPathA SetPath command always consists of a single request packet and corresponding response packet. Upon receiving a SetPath request packet,CObexServer will call SetPathIndication() on the MObexServerNotify-derived object passed into CObexServer::Start().SetPathIndication() passes two arguments: a CObex::TSetPathInfo reference and a descriptor reference. All the necessary information is encoded the TSetPathInfo object, and the descriptor isunused at this time.TSetPathInfo consists of fields corresponding to the additionalheader information encoded into a SetPath request packet (the Flags andConstants fields defined in section 3.3.6 of the OBEX specification), plusthe contents of the Name header if a Name header was included in therequest packet.

The SetPath flags are very simple; bit 0 is set if the OBEXserver is expected to ‘back up’ by a level before acting on the rest of theSetPath request information. Bit 1 is set to indicate that the OBEX servershould not create a directory of the name provided in the Name headerif such a directory doesn’t already exist.A TBool member variable iNamePresent can be used to determine whether a Name header was included in the SetPath requestbefore accessing the iName descriptor member variable (this differentiates between the case where no name was present and the case where aNULL name was present). An illustration of how to access these fields isincluded in the code example below.The OBEX server application can take whatever action is appropriateupon receiving a SetPathIndication() before returning an errorcode to indicate the outcome of the SetPath command to the OBEX clientapplication.

Mapping between the Symbian error codes and the OBEXresponse codes is achieved in the usual way (see Table 10.5). Appropriateaction may mean navigating to a new directory in an actual file system,or something more abstract such as navigating to a conceptual ‘location’offering a different subset of service behaviour (for example, see the IrMCspecification or the Bluetooth Phone Book Access Profile).TInt CObexFtpServer::SetPathIndication(const CObex::TSetPathInfo&aPathInfo, const TDesC8& /*aInfo*/){TBool backUpDir = aPathInfo.Parent();TBool dontCreateDir = aPathInfo.iFlags&KObexDontCreateDir;TBool namePresent = aPathInfo.iNamePresent;OBEX IN SYMBIAN OS// Log the setpath indicationiTest.Printf(KObexSetPathIndication);iTest.Printf(KObexSetPathBefore, &(TPtrC(iFileSpec.DriveAndPath())));if(namePresent){iTest.Printf(KObexSetPathIndInfo1, &aPathInfo.iName);}iTest.Printf( KObexSetPathIndInfo2,(backUpDir?&KTrueText():&KFalseText()),(dontCreateDir?&KTrueText():&KFalseText()));// We want this to be an atomic operation, so work on a// copy of the current directory spec in case something// goes wrong.TParse curDir = iFileSpec;TInt err = KErrNone;// Back up if requested...if(backUpDir){err = curDir.PopDir();}// Move down a directory if requested...if(!err && namePresent){if(aPathInfo.iName == KNullDesC){// Special case where path is to be reset to rootcurDir.Set(KStartDirectory, NULL, NULL);}else{// Check whether the named directory exists as// sub-directory of current directoryTBool dirExists = EFalse;err = DirExists(curDir.DriveAndPath(), aPathInfo.iName,dirExists);if(!err && !dirExists){// Directory doesn’t exist//if(!dontCreateDir){// Directory doesn’t exist, but we’re// allowed to create it//err = iFileServer.MkDir(curDir.DriveAndPath());dirExists = err?EFalse:ETrue;}else{// Directory doesn’t exist, we’re not// allowed to create it331332OBEX//err = KErrIrObexRespForbidden;}}// Add directory if it exists or we’ve been// allowed to create itif(!err && dirExists){err = curDir.AddDir(aPathInfo.iName);}}}if(!err){// Finally, we get to change the current directory, as// stored in iFileSpec so long as we haven’t hit any// errors.iFileSpec = curDir;}// Log the outcome of the setpathiTest.Printf(err ? KSetPathError() : KSetPathSuccess(), err);iTest.Printf(KObexSetPathAfter, &(TPtrC(iFileSpec.DriveAndPath())));return err;}Example 10.20 Implementation ofMObexServerNotify::SetPathIndication()Handling AbortWhen the OBEX client application sends an Abort request packet toabandon some other ongoing OBEX command, CObexServer will callAbortIndication() on the MObexServerNotify-derived objectpassed into CObexServer::Start().In response to this indication, the OBEX server application needsto only take any action necessary to prepare itself to accept anotherOBEX command.

Since the protocol definition of OBEX permits no otherresponse but ‘Success’, AbortIndication()’s return value is void,and the CObexServer ensures that the response packet is always sentwith a ‘Success’ response code.Handling errorsWhen a problem occurs with an OBEX session that requires disconnection, CObexServer will call ErrorIndication() on theMObexServerNotify-derived object passed into CObexServer::Start(). ErrorIndication() passes a TInt parameter containing a Symbian error code to indicate the nature of the problem. Thefunction is purely informational, and has a void return value.OBEX IN SYMBIAN OS333Once the OBEX server application has been notified of the error,CObexServer will bring the transport down.

As a result, a TransportDownIndication() may be expected to follow soon after theErrorIndication().10.2.7 OBEX Sessions with Authentication and Directed ConnectionsAuthentication in OBEX has been touched on above in relation tothe Connect command and authentication challenge and authenticationresponse headers, and directed connections in relation to the Target, Whoand Connection ID headers. The Symbian OS OBEX implementation hassupport for authentication, and to a limited degree, directed connectionsalso.

In this section we will learn how to make use of these concepts inSymbian applications.AuthenticationSymbian OS supports OBEX authentication during the processing of OBEXConnect commands only; authentication for individual commands (suchas Put or Get) is not supported. This applies to both OBEX server andOBEX client implementations.If an OBEX client application or an OBEX server application wishesto authenticate a remote peer application while setting up an OBEXsession, it must provide a password to use for the challenge.

The samepassword must be provided to the remote peer application in order for itto successfully respond to the challenge, and so become authenticated.Note that the password is never transmitted over the link, but rather ahash value is sent based on (amongst other things) the password.If the local OBEX application might be challenged by some remoteOBEX application, the OBEX application must be prepared to providea response password on request – this will usually require some userinteraction.During the establishment of an OBEX session, it is possible to havethe OBEX client authenticate the OBEX server, or the OBEX serverauthenticate the OBEX client, or both, or neither.

The sequence of eventsin protocol terms for each of these possibilities is described in ‘Connect’in section 10.1.4.The means by which Symbian-based OBEX client and server applications may provide the challenge and response passwords to the OBEXstack is covered in the next sections.OBEX server authentication by an OBEX clientWe have already seen how a password may be passed as a parameterto a CObexClient when calling ConnectL().

This password is then334OBEXused to challenge the OBEX server to which the CObexClient is tryingto connect.OBEX client authentication by an OBEX serverBecause they cannot predict when an incoming connection attempt mayoccur, OBEX server applications implemented in Symbian OS should provide the challenge password before calling Start() on CObexServer.They do this by calling CObexServer::SetChallengeL(), passing ina descriptor containing the password. This password is used to challengeany OBEX client that attempts to connect to the OBEX server.Responding to authentication challengesBoth OBEX server applications and OBEX client applications in SymbianOS use exactly the same API mechanism to be informed of and respondto incoming authentication challenges. This is possible because CObexClient and CObexServer are both derived from the same base class,CObex.To enable OBEX applications to be informed that they are being challenged for authentication, they must implement a class called MObexAuthChallengeHandler.

The OBEX application must call CObex::SetCallBack(), passing in a reference to an instance of a class derivedfrom MObexAuthChallengeHandler.MObexAuthChallengeHandler is a simple mixin class, defining asingle pure virtual function GetUserPasswordL(). As an argument,GetUserPasswordL() passes a descriptor containing the authentication realm (the realm is an optional field intended for display to users,often blank in practice).When any authentication challenge is directed to the OBEX application, the CObexClient or CObexServer will call GetUserPasswordL() on the provided MObexAuthChallengeHandler-derivedobject to indicate that a password is required to complete authentication.On being challenged, an OBEX application will normally have toperform some user interaction to elicit the password from the user. TheOBEX application is not required to provide the response password byreturn of the GetUserPasswordL() function; rather, once the userinteraction is complete, the application calls into the CObexClient orCObexServer using the CObex::UserPasswordL() function.

However, if the response password is already known to the application,CObex::UserPasswordL() can be called back immediately fromwithin GetUserPasswordL(). UserPasswordL() takes a descriptorparameter which contains the response password. Once UserPasswordL() has been called following a GetUserPasswordL() upcall,the challenge will be responded to, and the connection process willproceed according to the normal protocol rules.OBEX IN SYMBIAN OS335If an OBEX application is challenged for authentication and it has notprovided a MObexAuthChallengeHandler, the authentication (andconsequently the connection) will fail.10.2.8 Directed ConnectionsIn the OBEX specification, directed connections provide a way in whichrequests and responses for an OBEX session can be routed to a particularOBEX server that can handle the requirements of the OBEX client in atransport-independent way.

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

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

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

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