Главная » Просмотр файлов » Symbian OS Explained - Effective C++ Programming For Smartphones (2005)

Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885), страница 42

Файл №779885 Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (Symbian Books) 42 страницаSymbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885) страница 422018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Instead, theytend to use the stream store or relational database APIs, which you can finddescribed in the system documentation. These higher-level componentshave been optimized to access the file server efficiently. When storingdata to file, they buffer it on the client side and pass it to the file server inone block, rather than passing individual chunks of data as it is received.Thus, taking the stream store for example, RWriteStream uses aclient-side buffer to hold the data it is passed, and only accesses the fileserver to write it to file when the buffer is full or if the owner of the streamcalls CommitL().

Likewise, RReadStream pre-fills a buffer from thesource file when it is created. When the stream owner wishes to accessdata from the file, the stream uses this buffer to retrieve the portions ofdata required, rather than calling the file server to access the file.When writing code which uses a server, it is always worth consideringhow to make your server access most efficient.

Take the file server, forexample: while there are functions to acquire individual directory entriesin the filesystem, it is often more efficient to read an entire set of entriesand scan them client-side, rather than call across the process boundary tothe file server multiple times to iterate through a set of directory entries.18611.15THE CLIENT–SERVER FRAMEWORK IN THEORYHow Many Outstanding Requests Can a ClientMake to a Server?A client session with a server can only ever have a single synchronousrequest outstanding. However, it can have up to 255 outstanding asynchronous requests. The message slots which hold these requests are eitherallocated to a single session or acquired dynamically from a systemwide pool, according to the overload of RSessionBase::CreateSession() used to start the session. See the discussion on RSessionBase in Section 11.4 for more details.11.16Can Server Functionality Be Extended?Server code can be extended by the use of plug-ins to offer differenttypes of service.

A good example of this is the Symbian OS file server,which can be extended at runtime to support different types of filesystemplug-in. The core Symbian OS filesystem provides support for local media(ROM, RAM and CF card) using a VFAT filing system, implemented asa plug-in, ELocal.fsy. Other filesystems may be added, for exampleto support a remote filesystem over a network or encryption of filedata before it is stored. These file system plug-ins may be installed anduninstalled dynamically; in the client-side file server session class, RFs,you’ll see a set of functions for this purpose (FileSystemName(),AddFileSystem(), RemoveFileSystem(), MountFileSystem()and DismountFileSystem()).The extension code should be implemented as a polymorphic DLL(targettype fsy) and must conform to the fsy plug-in interfacedefined by Symbian OS.

More information about the use of frameworkand plug-in code in Symbian OS, and polymorphic DLLs, can be foundin Chapter 13.Since they normally run in the same thread as the server, and areoften called directly from CServer::RunL(), it is important to notethat installable server extension plug-in modules must not have a negativeimpact on the performance or runtime stability of the server.11.17Example CodeFinally, here is an example of how a server may be accessed and used.It illustrates how a client thread creates a session with the Symbian OSfile server.

The file server session class, RFs, is defined in f32file.h,and to use the file server client-side implementation you must linkagainst efsrv.lib.SUMMARY187Having successfully created the session and made it leave-safe usingthe cleanup stack (as described in Chapter 3), the sample code submits a request to the file server, using RFs::Delete(). This function wraps the single descriptor parameter and passes it to the synchronous overload of RSessionBase::SendReceive().

Followingthis, it creates an RFile subsession of the RFs session, by callingRFile::Create(). It then calls RFile::Read() on the subsession, which submits a request to the file server by wrapping a call toRSubSessionBase::SendReceive(), passing in the descriptorparameter that identifies the buffer which will receive data read fromthe file.RFs fs;User::LeaveIfError(fs.Connect());CleanupClosePushL(fs); // Closes the session in the event of a leave_LIT(KClangerIni, "c:\\clanger.ini");// Submits a delete request to the serverUser::LeaveIfError(fs.Delete(KClangerIni));RFile file; // A subsessionUser::LeaveIfError(file.Create(fs, KClangerIni,EFileRead|EFileWrite|EFileShareExclusive));// Closes the subsession in the event of a leaveCleanupClosePushL(file);TBuf8<32> buf;// Submits a request using the subsessionUser::LeaveIfError(file.Read(buf));CleanupStack::PopAndDestroy(2, &fs); // file, fs11.18SummaryThis chapter explored the theory behind the Symbian OS client–serverframework.

It is quite a complex subject, so the chapter was split into anumber of short sections to allow it to be read at several different levels,depending on whether the information is required to use a server or towrite one. The sections covered the following:• The basics of the client–server framework and why it is used to shareaccess to system resources and protect their integrity.• The thread model for a client–server implementation. The client andserver run in separate threads and often the server runs in a separateprocess; this isolates the system resource within a separate addressspace and protects it from potential misuse.

Symbian OS threads andprocesses are discussed in Chapter 10.188THE CLIENT–SERVER FRAMEWORK IN THEORY• The mechanism by which data is transferred between the clientand server, using inter-thread data transfer. This uses inter-processcommunication (IPC) when the client and server run in differentprocesses, and there are potential runtime overheads associated withIPC data transfer.• The main classes which make up the Symbian OS client–serverframework (RSessionBase, C(Sharable)Session, CServer,DSession, RMessage and RSubSessionBase), their main roles,features, fundamental methods and interactions.• Server startup (which is examined in more detail in the next chapter)and shutdown, either when all clients have disconnected normally oras a result of the death of either the client or server.• The overheads associated with using a client–server architecture,such as the number of kernel resources consumed by having multipleopen sessions with a server, and the potential impact of using activeobjects with lengthy RunL() event handlers within the server.• Example code using F32, the file server, as an example of a typicalSymbian OS client–server model.The following chapter uses a detailed code example to illustrate a typical server, its client-side implementation, and its use by a calling client.12The Client–Server Frameworkin PracticeKill the lion of NemeaKill the nine-headed HydraCapture the Ceryneian HindKill the wild boar of ErymanthusClean the stables of King AugeasKill the birds of StymphalisCapture the wild bull of CreteCapture the man-eating mares of DiomedesObtain the girdle of Hippolyta, Queen of the AmazonsCapture the oxen of GeryonTake golden apples from the garden of HesperidesBring Cerberus, the three-headed dog of the underworld, to the surfaceThe Twelve Labors of HerculesThis chapter works through the code for an example client and server toillustrate the main points of the Symbian OS client–server architecture,which I discussed in detail in Chapter 11.

This chapter will be of particularinterest if you plan to implement your own server, or if you want to knowmore about how a client’s request to a server is transferred and handled.The code examines the typical features of a client–server implementation using a transient server, which is started by its first client connectionand terminates when its last outstanding client session closes, to save system resources. I’ll take the main elements of client–server code in turn anddiscuss the most important sections of each.

You can find the entire set ofsample code on the Symbian Press website (www.symbian.com/books).The bootstrap code used by a client to start a server can be quite complexand you may find it helps to download this example and step through thecode to follow how it works.As in the previous chapter, I discuss the client–server model only forSymbian OS releases up to and including v7.0s (the code samples inthis chapter use the client–server APIs from Symbian OS v7.0). Some of190THE CLIENT–SERVER FRAMEWORK IN PRACTICEthe APIs have changed from Symbian OS 8.0 onwards and, although theconcepts are generally the same, I’ve decided to concentrate solely on thereleases available at the time of going to press, rather than confuse matters.Client–server code can be notoriously complicated, so I have keptthe services provided by the server as simple as possible. This comes,perhaps, at the expense of making the example code rather contrived; myclient–server example provides a software representation of the twelvelabors of the Greek hero Hercules.1 For each labor, I’ve exported afunction from a client-side implementation class, RHerculesSession.These functions send a request to the server to perform the necessaryheroic activity.

The client-side implementation is delivered as a sharedlibrary DLL (client.dll) – callers wishing to use the functionalityprovided by server should link to this. The server code itself is built intoa separate EPOCEXE component (shared library DLLs and targettypeEPOCEXE are discussed in Chapter 13).12.1Client–Server Request CodesA set of enumerated values is used to identify which service the clientrequests from the server. These values are quite straightforward and aredefined as follows:enum THerculeanLabors{ESlayNemeanLion,ESlayHydra,ECaptureCeryneianHind,ESlayErymanthianBoar,ECleanAugeanStables,ESlayStymphalianBirds,ECaptureCretanBull,ECaptureMaresOfDiomedes,EObtainGirdleOfHippolyta,ECaptureOxenOfGeryon,ETakeGoldenApplesOfHesperides,ECaptureCerberus,ECancelCleanAugeanStables,ECancelSlayStymphalianBirds};Later in the chapter you’ll see these shared request ”opcodes” passedto an overload of RSessionBase::SendReceive() on the client sideand stored in the corresponding server-side RMessage object (whichrepresents the client request) to identify which service the client hasrequested.1If nothing else, this chapter will prepare you well for a pub quiz question about theHerculean labors.CLIENT BOILERPLATE CODE19112.2 Client Boilerplate CodeMuch of the client-side implementation is made up of the API usedby callers to submit requests to the server.

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

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

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

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