quick_recipes (779892), страница 28

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

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

Also note, they won’t actually check if the filename specified existsin the file system.The base URI specified as the first parameter for CUri8::ResolveL() must either be empty or in absolute form, otherwise ResolveL()will leave with KUriErrBadBasePath.CUri8::SetComponentL() does not automatically encode thecomponents specified. Applications specifying components with reservedNETWORKING157URI characters must call EscapeUtils::EscapeEncodeL() to ensureproper encoding. Interestingly, components can also be removed from aURI with CUri8::RemoveComponentL().A fourth alternative way of creating a URI is to use UriUtils::CreateUriL(), which takes a 16-bit descriptor as parameter.

Moreinformation about this method can be found in the Symbian DeveloperLibrary.4.3.6 Intermediate Recipes4.3.6.1Listen for an Incoming Connection Using TCPAmount of time required: 20 minutesLocation of example code: \Networking\TCPListenRequired library(s): esock.lib, insock.libRequired header file(s): es_sock.h, in_sock.hRequired platform security capability(s): NetworkServicesProblem: You need to listen for an incoming connection using TCP.Solution: Use RSocket::Listen() and RSocket::Accept() onan opened socket to listen for incoming TCP requests and establishconnection with a remote peer.#include <es_sock.h> // RSocketServ, RSocket et al. (link to esock.lib)#include <in_sock.h> // KAfInet et al (link to insock.lib)void SetupListeningSocketL(){// Open the listening socketUser::LeaveIfError(iSockListen.Open(iSockServ, KAfInet, KSockStream, KProtocolInetTcp, iConn));// Bind the listening socket to a local addressTInetAddr localAddr(INET_ADDR(127, 0, 0, 1), 8000);User::LeaveIfError(iSockListen.Bind(localAddr));// Put the socket in listening modeUser::LeaveIfError(iSockListen.Listen(4));}#include <es_sock.h> // RSocketServ, RSocket et al.

(link to esock.lib)#include <in_sock.h> // KAfInet et al (link to insock.lib)void SetupActiveSocketL(){// Open the connecting socketUser::LeaveIfError(iSockActive.Open(iSockServ, KAfInet, KSockStream, KProtocolInetTcp, iConn));// Connect to the listening socket158SYMBIAN C++ RECIPES// already running on 127.0.0.1:8000TInetAddr connectAddr(INET_ADDR(127, 0, 0, 1), 8000);TRequestStatus status;iSockActive.Connect(connectAddr, status);// Wait for Connect to finishUser::WaitForRequest(status);// Check if there was any errorUser::LeaveIfError(status.Int());}#include <es_sock.h> // RSocketServ, RSocket et al.

(link to esock.lib)#include <in_sock.h> // KAfInet et al (link to insock.lib)void AcceptConnectionL(){// Create a 'blank' socket.// This will be used to accept// the connect request from iSockActiveRSocket sockBlank;User::LeaveIfError(sockBlank.Open(iSockServ));CleanupClosePushL(sockBlank);// Accept any incoming connect request// This will connect sockPassive with// sockActiveTRequestStatus status;iSockListen.Accept(sockBlank, status);// Wait for Accept to completeUser::WaitForRequest(status);// Check if there was an errorUser::LeaveIfError(status.Int());// iSockActive is now connected// with sockBlank, so we can exchange data_LIT8(KHello, "hello");iSockActive.Write(KHello, status);User::WaitForRequest(status);User::LeaveIfError(status.Int());TBuf8<10> recvBuf;TSockXfrLength len;sockBlank.RecvOneOrMore(recvBuf, 0, status, len);User::WaitForRequest(status);User::LeaveIfError(status.Int());ASSERT(recvBuf == KHello);CleanupStack::PopAndDestroy(&sockBlank);}Discussion: RSocket::Listen() takes an integer parameter that specifies how many incoming TCP connection requests can be queued.

Anyincoming request crossing the listen queue limit will be rejected. You willneed to tweak the listen queue size depending on the application you arewriting.NETWORKING159RSocket::Accept() takes what is known as a ‘blank’ socket asa parameter. The blank socket is an RSocket instance that is openedwithout specifying any protocol attributes.

Once Accept() completeswithout any error, the blank socket becomes a full-fledged TCP socket,connected to the remote peer that requested the connection and readyto exchange data. If multiple incoming socket requests are queued inthe listening socket’s listen queue, the application can call Accept()multiple times, passing a new ‘blank’ socket each time to establishconnection with the remote peers in waiting.4.3.6.2Observe Connection StatusAmount of time required: 20 minutesLocation of example code: \Networking\ConnectionStatusRequired library(s): esock.libRequired header file(s): es_sock.h, nifvar.hRequired platform security capability(s): NoneProblem: You want to monitor the status of a connection.Solution: Use RConnection::ProgressNotification() to monitor the status of a connection.#include <nifvar.h> // link to esock.libvoid CConnectionProgressObserver:: RequestProgressNotification(){ASSERT(!IsActive());iConnection.ProgressNotification(iProgressBuf, iStatus);SetActive();}void CConnectionProgressObserver::RunL(){TInt error = iStatus.Int();if (KErrNone == error){iConnection.ProgressNotification(iProgressBuf, iStatus);SetActive();}iNotify->OnProgressNotificitionL(iProgressBuf(), error);}void CConnectionStatusAppUi::ProgressNotificitionL(const TNifProgress&aProgress, TInt aError){if (KErrNone != aError){160SYMBIAN C++ RECIPES// Error calling ProgressNotification.

Check if the// connection is open}else{// Examine generic progress received.// See nifvar.hswitch (aProgress.iStage){case KConnectionUninitialised:// The connection has closed and returned to// uninitialized state. Retrieve the// last progress and decide whether to// restart the connectionTNifProgress progress;User::LeaveIfError(iConnection.LastProgressError(progress));...break;case KLinkLayerClosed:case KConnectionClosed:case KConnectionFailure:// Connection disconnected/closed. We’ll eventually hit// KConnectionUninitialised stage...break;case KLinkLayerOpen:// Link layer opened, note this doesn’t mean// the connection is ready for data transfer// as it still might be busy acquiring a network// address, e.g.

WLAN...break;}}}Discussion: It is common for a connection state to change faster thanit can be handled. RConnection::LastProgressError() can beused to determine any reason for disconnection, along with the stagewhen it happened.When a connection fails, care must be taken to determine the feasibilityof retrying the connection (by checking TNifProgress::iError), notonly because it might potentially be a CPU-intensive, hence batterydraining, operation, but also because the user of the phone can explicitlyrequest the connection termination, for example using a connectionmanager tool, found in both UIQ and S60. Unfortunately, there is noall-encompassing guideline.

However, for certain errors, like KErrAccessDenied (-21) or KErrConnectionTerminated (-17210),the application should not retry at all, since this usually indicates auser-initiated disconnect through a connection manager.NETWORKING161Note that besides the generic progress values defined in nifvar.h,each bearer technology, for example WLAN/GPRS implementation, isfree to provide its own set of progress values.4.3.6.3Get Active Connection InformationAmount of time required: 15 minutesLocation of example code: \Networking\ConnectionStatusRequired library(s): esock.libRequired header file(s): es_sock.hPlatform security capability(s): NoneProblem: You want to retrieve information about an existing connection.Solution: Use RConnection::GetXyzSetting() methods to retrieveinformation about an existing connection.#include <es_sock.h> // link to esock.libvoid DisplayConnectionInfo(){TUint32 aIntValue;TBuf<70> aDesValue;// Read IAP Id_LIT(KIAPId, "IAP\\ID");User::LeaveIfError(iConnection.GetIntSetting(KIAPId, aIntValue));// Read IAP Name_LIT(KIAPName, "IAP\\Name");User::LeaveIfError(iConnection.GetDesSetting(KIAPName, aDesValue));// Read the service type, e.g.

IAP_SERVICE_TYPE_LIT(KIAPServiceType, "IAP\\IAPServiceType");User::LeaveIfError(iConnection.GetDesSetting(KIAPServiceType,aDesValue));// Read the name of the service tableTBuf<100> serviceTableName;_LIT(KServiceTableName, "%S\\Name");serviceTableName.Format(KServiceTableName, &aDesValue);User::LeaveIfError(iConnection.GetDesSetting(serviceTableName,aDesValue));}Discussion: The GetXyzSetting() methods read the CommsDat settings using <table name>\<field name> format. The table and fieldnames are defined in cdbcols.h.As an example, reading ‘IAP\ID’ gives the id of the IAP and ‘IAP\IAPServiceType’ gives the service type, for example LANBearer.162SYMBIAN C++ RECIPESWhat may go wrong when you do this: During testing, the S60 3rdEdition Maintenance Release 3 emulator failed to retrieve the IAP idusing GetIntSetting().

The other settings retrieval worked justfine.4.3.6.4Use Secure SocketAmount of time required: 20 minutesLocation of example code: \Networking\SecureSocketsRequired library(s): esock.lib, securesocket.libRequired header file(s): es_sock.h, in_sock.h, securesocket.hPlatform security capability(s): NetworkServicesProblem: You want to use a secure connection.Solution: Use CSecureSocket to establish a secure connection andexchange data with a remote peer.// RSocketServ, RConnection et al (link to esock.lib)#include <es_sock.h>// KAfInet et al (link against insock.lib)#include <in_sock.h>// CSecureSocket (link against securesocket.lib)#include <securesocket.h>void CSecureSocketAppUi::RunL(){User::LeaveIfError(iStatus.Int());switch (iState){case EStartingConnection:User::LeaveIfError(iSocket.Open(iSockServ,KAfInet, KSockStream, KProtocolInetTcp, iConn));iSocket.Connect(iAddress, iStatus);iState = EConnecting;SetActive();break;case EConnecting:iSecureSocket = CSecureSocket::NewL(iSocket, KSSLProtocol);// Set the domain name of the host that we are connecting to.// Note usage of name as opposed to IP address.User::LeaveIfError(iSecureSocket->SetOpt(KSoSSLDomainName,KSolInetSSL, KSecureHostName));// Enable user prompting when an// un-trusted certificate is receivedUser::LeaveIfError(iSecureSocket->SetDialogMode(EDialogModeAttended));iSecureSocket->StartClientHandshake(iStatus);iState = EHandShaking;SetActive();NETWORKING163break;case EHandShaking:iSecureSocket->Send(KSendData, iStatus);iState = ESendData;SetActive();break;case ESendData:iSecureSocket->RecvOneOrMore(iRecvBuf, iStatus, iRecvLen);iState = EReceiveData;SetActive();break;case EReceiveData:// Do something with the received data...// Then cleanupiSecureSocket->Close();delete iSecureSocket;iSecureSocket = NULL;iState = EUninitialized;break;default:User::LeaveIfError(KErrUnknown);break;}}Discussion: The CSecureSocket implementation requires a TCP socketalready connected to the remote peer before a secure session can beinitiated with that peer.

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

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

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

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