Главная » Просмотр файлов » Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007

Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887), страница 62

Файл №779887 Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (Symbian Books) 62 страницаWiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887) страница 622018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

For this example server, a text buffer isassociated with each session, and the ConstructL() function createsthe buffer as an RBuf descriptor.Processing messages from the clientWhen a server receives a message from a client, the server creates aninstance of a class called RMessage2 to hold the message contents. Thenthe server invokes the ServiceL() method of the appropriate sessionobject – supplying the RMessage2 object as its argument.The following shows the session command handler for the textbuffserv example:void CTextBuffSession::ServiceL(const RMessage2& aMessage){DispatchMessageL(aMessage);aMessage.Complete(KErrNone);}void CTextBuffSession::DispatchMessageL(const RMessage2& aMessage){// check for session-relative requestsswitch (aMessage.Function()){case ETextBuffAddText:TBuf<200> tmp;aMessage.ReadL(0,tmp);AddTextL(tmp);break;case ETextBuffGetText:TPtrC buff = GetText();aMessage.WriteL(0,buff);break;case ETextBuffReset:Reset();break;case ETextBuffBackSpace:BackSpaceL(aMessage.Int0());break;case ETextBuffCloseSession:CActiveScheduler::Stop();break;default:ClientPanic(aMessage,EInvalidCommand);break;}}CLIENT–SERVER EXAMPLE317// Handles leaves from CTextBuffSession::DispatchMessageL()// A bad descriptor error implies a badly programmed client, so panic it// Report other errors to the client by completing the outstanding request//with the errorvoid CTextBuffSession::ServiceError(const RMessage2& aMessage, TIntaError){if (KErrBadDescriptor==aError)ClientPanic(aMessage,EInvalidDescriptor);elseaMessage.Complete(aError);}void CTextBuffSession::Reset(){iTextBuff.Zero();}void CTextBuffSession::AddTextL(TDesC& aText){if ( (aText.Length() + iTextBuff.Length()) > iTextBuff.MaxLength())User::Leave(KErrTooBig);elseiTextBuff.Append(aText);}void CTextBuffSession::BackSpaceL(TInt aNumChars){if (aNumChars <= iTextBuff.Length()){TInt newLength = iTextBuff.Length() - aNumChars;iTextBuff.SetLength(newLength);} elseUser::Leave(KErrTooBig);}TDesC& CTextBuffSession::GetText(){return iTextBuff;}ServiceL() invokes another method, DispatchMessageL(), tohandle the message.

Below are some of the key RMessage2 methods foraccessing the command code and arguments of the message sent, as wellas some other functionality:• Function() returns the command code that was specified viathe first argument of the client object’s SendReceive()/ Send()function.• Int0(), Int1(), Int2(), and Int3() return, as integers, the four32-bit values passed in the second argument of the SendReceive()and Send() function.• Write() writes data to descriptors passed as arguments from theclient via SendReceive() and Send(). This method will bediscussed in more detail shortly.

A leaving version of this function,WriteL(), also exists.318CLIENT–SERVER FRAMEWORK•Read() reads data from descriptors passed as arguments from theclient via SendReceive() and Send(). This method will also bediscussed in more detail shortly. A leaving version of this function,ReadL(), also exists.•Panic(TDesC& aCategory,TInt aCode) panics the client-sidethread that sent the message to this session. This is usually done whenthe server detects coding errors in the client.• Complete(TInt aReason) is called by the server when it hascompleted processing of the message. The passed value is the statusreturned by the SendReceive() method that sent the message.•HasCapability() checks to see if the client that sent the message has a specified capability.

For example, aMessage.HasCapability(ECapabilityWriteDeviceData) (assuming aMessageis an RMessage2 from the client) would return ETrue if the clientprocess has the WriteDeviceData capability (see Chapter 7 formore on capabilities). System servers will use this method in caseswhere the server only wants to perform certain operations on behalfof clients with specific capabilities.

A leaving version of this function,HasCapabilityL(), also exists.If ServiceL() leaves due to an error, the framework calls the virtual session method ServiceError(), passing it the current sessionmessage as well as the leave code. The example overrides this methodto cause a client-side panic to occur if it detects that the leave wasdue to a bad client-side descriptor. Otherwise, ServiceError()completes the RMessage2 message with the error code by callingRMessage2::Complete().ClientPanic() in our example is implemented as follows:void CTextBuffSession::ClientPanic(const RMessage2& aMessage,TInt aPanic)const{_LIT(KTextBuffServSess,"CTextBuffSession");aMessage.Panic(KTextBuffServSess,aPanic);}Transferring data between the client and serverIn many cases, a client specifies a buffer in the client memory space asan argument to the command that it sends to the server.

This could be abuffer for the server to either read input from (AddText() uses this in ourexample), or write output to (as our GetText() command does). Sincethe client and server reside in different threads and, more importantly,could also reside in different processes, the server must use inter-threaddata accesses rather than direct access through the client pointers.CLIENT–SERVER EXAMPLE319When the client sends a buffer to the server, it is in the formof a pointer to a descriptor. The server cannot directly read andwrite using this descriptor if they are in different processes, whichis typically the case for servers. Doing so would result in a panic,and the data would not be available in the place specified by thepointer anyway since the client process it belongs to is not currentlyactive.

This limitation is there to provide security since the operatingsystem does not want one process to intentionally or unintentionally corrupt another. Section 3.5.6 discusses this in more detail. Toaccess these buffers, the server uses the RMessage2::Read() andRMessage2::Write() methods, passing the index of the parameter in which the client placed the buffer in the first argument, and adescriptor to read the data from, or write the data to, in the secondargument.Returning to the example server, DispatchMessageL() calls RMessage2::Function() to determine which command code was sent bythe client, and then handles the command appropriately.For the command ETextBuffAddText, the first argument of the message is a pointer to the client descriptor that contains the text to be addedto the session’s text buffer.

The text is read using RMessage2::Read()as follows:TBuf<200> tmp;res = Read(0,tmp);This reads the data from the descriptor pointer supplied by the client inits first TIpcArg argument (index 0) sent via SendReceive() in theclient method RTextBuff::AddText(). This is an inter-thread readand thus will work properly when reading from a client address space ineither the same or (as in this case) a different process.If the pointer in the message argument specified does not point to a validdescriptor, the Read() function will return an error. The error is handledby a utility function, which concludes by calling RMessage2::Panic()to panic the client thread.Once the text has been read, AddText() (the server-side one)is called to append the text to the text buffer associated with thatsession.In the case of ETextBuffGetText, the first argument is a pointer tothe client-side descriptor to which the text is to be written.

The text iswritten using the RMessage2::Write() method.ETextBuffBackSpace is an example of a case where the firstargument is an integer rather than a pointer. This integer, read by theRMessage2::Int0() method, indicates the number of characters tobackspace in the text buffer.320CLIENT–SERVER FRAMEWORK10.3.3 Example Use of TextBuffSrvHere is an example of how a client program might use TextBuffSrv:LOCAL_C void ClientProgL(){RTextBuff textbuff;TBuf<100> t;TInt ret=textbuff.Connect();User::LeaveIfError(ret);textbuff.Reset();textbuff.AddText(_L("Hello"));textbuff.GetText(t);Console->Printf(_L("GetText text=%S\n"),&t);textbuff.AddText(_L("Again"));textbuff.GetText(t);Console->Printf(_L("GetText text=%S\n"),&t);textbuff.BackSpace(3);textbuff.AddText(_L("xxxx"));t.Zero();textbuff.GetText(t);Console->Printf(_L("GetText text=%S\n"),&t);textbuff.Reset();textbuff.AddText(_L("Start"));textbuff.GetText(t);Console->Printf(_L("GetText text=%S\n"),&t);textbuff.Close();}The output of this would be:GetTextGetTextGetTextGetTexttext=Hellotext=HelloAgaintext=HelloAgxxxxtext=Start10.3.4 Shutting Down the ServerIn our example the server is never shut down, and many system serversin Symbian OS behave in this way.

However, for applications, it is morecommon for the servers to be transient – that is, they only run while theyare being used to save on system resources.If our server always has just one client, and we want the server tobe shut down once the client has finished with it, we can override theRSessionBase Close() method in our client class as follows:void RTextBuff::Close(){SendReceive(ETextBuffCloseSession);RHandleBase::Close();}CLIENT–SERVER EXAMPLE321Then in the server, you can include an additional case in ServiceL()to handle this close command:case ETextBuffCloseSession:CActiveScheduler::Stop();break;Stopping the active scheduler would cause CActiveScheduler::Start() to return (in StartServer()) and shut down the server, andadditionally clean up and exit the process.However, if you are servicing multiple clients (which is what serversare really meant for anyway), then you do not want to implement theClose() in this way, since you do not want one client to be able toclose the server.A good way to implement the shutdown in this case is to keep areference count that tells you how many clients currently have opensessions with the server (you can increment/decrement a reference countvariable in your server class as sessions are created and deleted).

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

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

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

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