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

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

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

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

To do this, a ‘priming record’ is created which contains the information against which tomatch.// To start the search, create a new record set, and add a record// containing the information to match against.CMDBRecordSet<CCDIAPRecord>* iapRecordSet = new (ELeave)CMDBRecordSet<CCDIAPRecord>(KCDTIdIAPRecord);CleanupStack::PushL(iapRecordSet);// Match against LAN Bearers.LIT(KBearerType, "LANBearer");TPtrC bearerType(KBearerType);// Create the record to fill with the data to matchCCDIAPRecord* primingRecord = static_cast<CCDIAPRecord*>(CCDRecordBase::RecordFactoryL(KCDTIdIAPRecord));primingRecord->iBearerType = bearerType;// Add it to the new record setiapRecordSet->iRecords.AppendL(primingRecord);// Ownership is passed to the recordsetprimingRecord = NULL;170IP AND RELATED TECHNOLOGIES//Searchif(iapRecordSet->FindL(*iDb)){//The iapRecordSet->iRecords.Count() will now reflect the number of// records foundTInt iapRecordsFound = iapRecordSet->iRecords.Count();// The records can now be accessed as before...}When searching through records in CommsDat, it is more efficient touse Record IDs than names.The type of the IAP is stored as a field in the record set, but to accessthe user settings the information in the service table is required.All objects must be cleaned up once finished with:CleanupStack::PopAndDestroy(2);// iapTable, dbsInformation about active IAPs (i.e.

those which are currently connected) can also be retrieved via the RConnection API without needingto use the CommsDat APIs. This is discussed later in section 6.5.3.Connection preferencesOnce the correct IAP has been selected, a connection preference object,a TCommDbConnPref, must be created to store the IAP ID and otherinformation (defined in CommDbConnPref.h):TCommDbConnPref iConnPref // class member;if(chosenIAP != KErrNotFound){iConnPref.SetIapId(chosenIAP);}In some cases, the IAP ID is all that needs to be provided, however, if youare explicitly providing an IAP it also pays to ensure that any promptingof the user is disabled.iConnPref.SetDialogPreference(ECommDbDialogPrefDoNotPrompt);The different possibilities for prompting are defined in TCommDbDialogPref:/** Preference set to prompt user.

*/ECommDbDialogPrefPrompt,/** Preference set to warn user. */ECommDbDialogPrefWarn,/** Preference set not to prompt user. */ECommDbDialogPrefDoNotPrompt,/** Preference set to prompt user when in wrong mode. */ECommDbDialogPrefPromptIfWrongModeNETWORK BEARER TECHNOLOGIES IN SYMBIAN OS171To limit the set of available IAPs selectable by the user to a particular setof technologies, you can also configure the bearer set in the connectionpreference:connPref.SetBearerSet(ECommDbBearerWcdma | ECommDbBearerWLAN |ECommDbBearerPAN )Where the available subset is:ECommDbBearerCSDECommDbBearerWcdma or ECommDbBearerGPRS – these are equivilentECommDbBearerPSDECommDbBearerVirtualECommDbBearerPANECommDbBearerWLANIf a particular technology is unavailable, then the system will automatically remove it from the available options.6.3.3 Starting the ConnectionOnce the connection preferences have been configured, they can be usedto start the network connection.

We have already discussed starting theconnection without using connection parameters like so:iConn.Start(iStatus);Using the connection preferences gives the application control overwhich IAP is selected and over the user interaction (prompting etc.) likethis:iConn.Start(iConnPref, iStatus);As stated earlier, if the connection fails the error is returned asynchronously via the TRequestStatus. If the connection is startedsuccessfully, this will complete with KErrNone once the connection hasreached the KLinkLayerOpen stage. More detailed information aboutthe state of the connection can be gathered using the progress-reportingAPIs discussed in section 6.5.1.Put together, the code to start a known IAP explicitly looks like this:// these are typically member variables of a class// this is important, as the Start() call is asynchronous so// iConnPref must not be a local variableRSocketServ iSockServ;RConnection iConn;TCommDbConnPref iConnPref;CSomeClass::StartConnectionL(TInt aChosenIap){172IP AND RELATED TECHNOLOGIESUser::LeaveIfError(iSockServ.Connect());User::LeaveIfError(iConn.Open(iSockServ));iConnPref.SetIapId(aChosenIap);iConnPref.SetDialogPreference(ECommDbDialogPrefDoNotPrompt);iConn.Start(iConnPref, iStatus);SetActive();}Setting multiple IAPsIt is possible for an application to provide a set of connection preferencesto be tried in succession until one succeeds.

This is done using theTCommDbMultiConnPref class. The following code will iterate throughthe IAPs with IDs 1, 2 and 3:TCommDbConnPref connPref1;connPref.SetIapId(1);TCommDbConnPref connPref2;connPref.SetIapId(2);TCommDbConnPref connPref3;connPref.SetIapId(3);TCommDbMultiConnPref iMultiConnPref;iMultiConnPref.SetPreference(1, connPref1);iMultiConnPref.SetPreference(2, connPref2);iMultiConnPref.SetPreference(3, connPref3);iMultiConnPref.SetConnectionAttempts(3);Supporting different bearersOne of the important things to remember is that if your application doesnot know or care how it connects to a network (i.e., it does not care whichIAP is used), then it must be able to handle the different characteristicsthat different bearers display.

In particular, any timers relating to sending/receiving data must be very carefully chosen, although our advice is todispense with them altogether and rely on network layer timeouts wherepossible. Obviously for unreliable protocols like UDP this is not possible;however for TCP there should be no need for an application to limit theduration of a socket operation using its own timer. Any dependencies ondata rates or network latencies much be carefully handled. In summary,remember not to depend upon certain behavior patterns just because theyare exhibited by one type of network, and avoid building behavior thatrelies on certain network performance characteristics into the applicationwherever possible. This is particularly important with GPRS networks,where latencies can be in excess of 500 ms.You should also be aware that there is a timer with a number of modesthat measures how long a connection has been inactive, and can terminate a connection after a period of inactivity – section 6.3.4 contains moreNETWORK BEARER TECHNOLOGIES IN SYMBIAN OS173details on this.

You should be aware that the connection may be terminated for a number of reasons, one of which is the expiry of the idle timer.Using an existing connectionIn most cases, if you wish to have your application use an existing connection, it should call RConnection::Start() with the appropriateIAP information, just as it would if the connection were not alreadystarted. This increments the usage counter on the connection to ensurethat it is aware of the new client.The RConnection::Attach() method can be used to join anexisting connection – however, it is far more simple just to use Start()as detailed above, as this works whether or not the connection is alreadystarted.6.3.4 Stopping the Network ConnectionThere are a number of different ways for a network connection to beterminated. Of these, forced disconnection is the least desirable due toits potential for disrupting the operation of other applications on thedevice. In most cases, you should indicate that you do not need theconnection any longer, then let the system arbitrate between applicationsand eventually terminate the connection.Forced disconnectionRConnection::Stop() allows an application to terminate a networkconnection immediately.

This should be rarely, or ideally never, be usedas there may be other applications using the same connection, who willhave their connection terminated. Stop() also requires the NetworkControl capability, which is part of the manufacturer capability set,due to its potential to disrupt the operation of other applications on thedevice.err = iConn.Stop();This version of Stop() causes sockets using the connection tobe errored with KErrCancel. There is another version – used by theconnection manager applications on the UI platforms – that causes KErrConnectionTerminated to be returned instead.

In this case the userhas explicitly terminated that connection and therefore if you receive thiserror code from a connection you are using, you should not attempt torestart it.Note that Stop() can return an error, which may happen, for example,if the connection has not yet been started (KErrNotReady) or if the174IP AND RELATED TECHNOLOGIESconnection is active but cannot be stopped in its current state (KErrPermissionDenied).Automatically by the system due to lack of useThis is the preferred way to let connections shut down, as it is basedon the usage of the connections by all applications.

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

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

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

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