Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887), страница 62
Текст из файла (страница 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).