Главная » Просмотр файлов » Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356

Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879), страница 36

Файл №779879 Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (Symbian Books) 36 страницаIssott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879) страница 362018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

It is employed wherethe client and server are separated into different execution, or memory management, contexts. It represents and encapsulates the client’s14 Thispattern is one way in which Singleton (see page 346) is implemented on SymbianOS.15 This serves as the synchronization point, sequencing messages from different clients tothe server so they can be executed in order.186PROVIDING SERVICESend-point of a session between the server and this particular client. Itis responsible for marshaling client calls into a request message thatare sent to the message queue in the server context.• Request Message (RMessage2): The request message allows RequestCompletion (see page 104) to be extended, not only to allow aTRequestStatus to be passed between the client and server but alsoto pass any context information about a specific method invocationon a client session, such as the method parameters.• Server Session (CMyServerSession): This session represents andencapsulates the server end-point of the connection between theserver and a single client.

It is responsible for de-marshaling a requestmessage and making the equivalent call on the server. It is furtherused to manage other client-specific information the server may need.DynamicsHere we discuss the typical use cases that are realized in this pattern. Thebehaviors we consider are:• starting and connecting to a server• making a simple synchronous service request• making an asynchronous service request• observing state changes in the service• canceling a long-running service request• disconnecting from the server.A number of simplifications are made in the diagrams so that the detailof how the client–server framework provided by Symbian OS operatesdoesn’t get in the way of your understanding of how an implementationof this pattern should behave. In particular, the following things aretechnically incorrect but conceptually helpful:• The client–server framework behaves as an active scheduler for boththe client and the server process.• The request message, iMsg, sent between the client and the serverappears to be the same instance.Starting and Connecting to a ServerFigure 6.9 describes the interaction between the objects involved inloading and connecting to a server.Note that your server object must provide a name for itself whenit is first started.

This name is then used by clients to identify to theCLIENT–SERVER187Client Process:CClientActiveServer Process:RMyClientSessionClient–ServerFrameworkConnect()Create(”MyServer”)MyServer:CMyServerStart(”MyServer”)ReStart()Receive()iMsg(EConnect)SendReceive(iMsg)WaitForRequest(iMsg.iStatus)RunL()Completion of theconnect requestmessage causesthe client sessionto be resumedfrom its wait state.NewSessionL()aSession:CMyServerSessionComplete(iMsg.iStatus, KErrNone)ReStart()Receive()Figure 6.9Dynamics of the Client–Server pattern (first connection to a server)client–server framework the server to which they wish to connect. Thisname must be unique across the whole system and hence the Start()call fails if another server with the same name already exists.To prevent denial-of-service attacks from malware deliberately creating servers using your chosen server name, and hence provoking aKErrAlreadyExists error when your server later comes to be created,you have the option of prepending a ! to the front of your server name.

Toprevent misuse, your server process must have the ProtServ capabilityfor this to succeed.Making a Simple Synchronous Service RequestFigure 6.10 depicts what happens when a client makes a simple synchronous service request on a server.Making an Asynchronous Service RequestFrom the server’s perspective, all requests are made asynchronously.However, as we see in Figure 6.10, the client session blocks on the188Figure 6.10PROVIDING SERVICESDynamics of the Client–Server pattern (simple synchronous request)TRequestStatus it supplies when making what appears to the clientas a synchronous call. To make an asynchronous service request on aserver, a client must supply its own dedicated TRequestStatus to becompleted by the server. After the call has been made, the client canchoose to do one of two things:• When using a simple TRequestStatus, the client can wait on theTRequestStatus, thereby blocking its thread until the request iscompleted.• When using the TRequestStatus from an active object, the clientcan return execution control from its current operation.

When therequest is completed, the active object is scheduled to run and hencenotifies the client of the event.The second of these tactics is the most used as it allows the client’sthread to perform other tasks in parallel to the request being serviced bythe server. This is the tactic illustrated in Figure 6.11.Notice the way the server delegates the actual activity to a servantactive object. It is a design strategy that frees the server to respond to othermessages to maintain quality of service on behalf of all clients. The servantmakes use of the ‘Long Running Active Object’ variant of AsynchronousController (see page 148) to break up what would otherwise be a longCLIENT–SERVER189Server ProcessClient Process:RMyClientSession:CClientActiveClient–ServerFrameworkMyServer:CMyServeraSession:CMyServerSessionDoActivity(iStatus)iMsg(EDoActivity, iStatus)SendReceive(iMsg)The receipt of the activitymessage activates the server tobe run.

The server then createsan active object servant to dothe activity in the background.SetActive()RunL()ServiceL()DoActivityL()CServantStart(iMsg)iActivityMsg(iMsg)ReStart()Receive()RunL()DoNext()SelfComplete()Completion of the activitymessage causes the clientactive object to be run.RunL()DoNext()Complete(activityMsg, KErrNone)RunL()HandleActivityCompleteL()Figure 6.11 Dynamics of the Client–Server pattern (long-running asynchronous request)synchronous activity that would disrupt the entire server thread. The useof Asynchronous Controller regularly yields control back to the activescheduler so that higher-priority active objects get a chance to run.Canceling an Asynchronous Service RequestThere are a number of scenarios in which a client may wish to cancel anasynchronous service request that it has made.

This pattern must be ableto handle all these situations successfully. We summarize them here as:• Scenario 1: The service request hasn’t even begun to execute (but theclient does not know that at the point of requesting a cancellation).• Scenario 2: The service request is being dealt with by a servant activeobject in the server context when the cancellation request is received.190PROVIDING SERVICES• Scenario 3: The service request has already been completed andreplied to (but the client does not know that at the point of requestinga cancellation).In all situations, the important thing is that a TRequestStatus isonly completed once for the service request with which it is associated.To achieve this, the cancel use case is realized synchronously by sending a specific cancellation request to the server with its own separateTRequestStatus.There are two approaches corresponding to the choices the clientmade when making the asynchronous request:• If a simple TRequestStatus is used to make the activity request,then the cancel request is made before the client blocks the thread towait on the same activity TRequestStatus.• If an active object is used to make the activity request, then cancellation is achieved by canceling the active object which then waits onits TRequestStatus.In Scenario 1, the client session may have failed to create the resourcesneeded to send the original request message.

Alternatively, the server session may have received the activity request but failed to execute it. Eitherobject must have already completed the original TRequestStatus witha failure code. So the server has no pending activity to cancel. The serversimply acknowledges the cancel request by completing it with a successcondition code (KErrNone).In Scenario 2, the server must quickly abort the servicing of theoriginal activity request and complete it with a KErrCancel. The serveralso acknowledges the cancel request with a KErrNone.

Since thecancellation is being realized synchronously it is important that the serverresponse is immediate. So any expensive (in time) pre-cessation tasksshould be deferred until after the TRequestStatus is completed.In Scenario 3, the server must simply acknowledge the cancel requestmessage with KErrNone.

There is no pending activity request messageto be canceled.Figure 6.12 depicts Scenario 2. It shows a server that has just createda servant active object to carry out the activity when the cancellation notice arrives. Notice how the client active object waits on itsTRequestStatus until it is completed, in this case, with KErrCancel.Observing a Server’s StateMaking a call to observe a server’s state is similar to making any otherasynchronous request for information.

Of course one difference is thatthe client may only require to be notified of the state change insteadof receiving the changed information. In the second instance, the clientmust provide a placeholder for the information.CLIENT–SERVER191Client ProcessCClient:CClientActiveServer Process:RMyClientSession:CMyServerClient–ServerFrameworkiServant:CMyServerSessionCancel()DoCancel()The receipt of the cancel messageactivates the server to be run. Firstthe servant is called to cancel theactivity request message whilst theserver session completes thecancel request message.CancelActivity()iCancelMsg(ECancelActivity)Whilst the servant carries on the activityinside the server, the client requests acancellation of the activity.

Note howthe active object is used to initiate thecancellation and then waits on thecompletion of the activity message.SendReceive(iCancelMsg)WaitForRequest(iCancelMsg.iStatus)RunL()ServiceL()CancelActivity()Cancel()The completion of the activitymessage (with KErrCancel)causes the client activeobject to resume from itswaiting.Complete(activityMsg, KErrCancel)ReStart()Receive()Complete(iCancelMsg, KErrCancel)WaitForRequest(iStatus)Completion of the cancelmessage causes the clientsession to resume from itswaiting.Figure 6.12 Dynamics of the Client–Server pattern (cancellation of a pending asynchronous request)Disconnecting from a ServerDisconnection from the server is done in the same way as making anyother synchronous request. The client session sends an EDisconnectmessage to the server.

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

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

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

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