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

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

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

Note that problemsassociated with network access over ICS will apply to your application too.4.3.2.4Using WinSockThe WinSock method is the default connectivity solution in the S60 SDKand uses Windows sockets directly, bypassing the Symbian OS TCP/IPstack. The biggest advantage is that there is no special setup requiredat all, since the Symbian OS applications running under the emulatorare just clients to the Windows networking stack. The downside is thatsetting or retrieval of protocol-level options supported by the SymbianOS TCP/IP stack which are not present in the Windows stack will fail,besides features that are not supported on WinSock, like IP multicasting.Hence, be sure to pick the right connectivity method depending on theapplication you are developing.At the time of writing, there is no WinSock connectivity methodavailable for the UIQ 3 SDKs based on Symbian OS v9.x.4.3.3 HTTPThe HTTP framework in Symbian OS provides a HTTP client stack,supporting all standard HTTP 1.1 services and protocol-defined requests,including GET and POST.

The framework also supports compatibilitywith HTTP 1.0 servers, authentication (basic and digest) and secureconnections. Notable omissions include cookie management, cachingand content encoding. However, the framework supports an extensiblefilter mechanism that can be used to provide support for the above. Checkyour SDK documentation for more information.The HTTP framework is implemented as a client-side library inhttp.lib. The framework-related classes and so on are defined inhttp.h. HTTP requires access to a network connection; hence applications using the HTTP framework need NetworkServices platformsecurity capability.1424.3.4SYMBIAN C++ RECIPESInetProtUtilsThe InetProtUtils API is used to handle URIs, including constructingand modifying a URI, extracting URI components and utility parsingmethods.The Universal Resource Identifier (URI), described in RFC 2396, is aformatted string that identifies the location and name of a resource; forexample, a web address (in fact, a URI can be seen as an extended URL)or a file in the local file system.The InetProtUtils API is implemented in InetProtUtils.liband requires no platform security capability for usage.Note that all URI-related methods in InetProtUtils operate on8-bit descriptors, since a URI, by definition, can only be 8-bit UTF-8encoded text.

For convenience, the URI classes support a method calledDisplayFormL() where applicable, which returns the 16-bit Unicodeequivalent.4.3.5 Easy Recipes4.3.5.1Send/Receive Data Using TCP SocketsAmount of time required: 15 minutesLocation of example code: \Networking\TCPSendReceiveRequired library(s): esock.lib, insock.libRequired header file(s): es_sock.h, in_sock.hRequired platform security capability(s): NetworkServicesProblem: You want to send and receive data using TCP sockets.Solution: Use RSocket::Connect() to connect to a remote peerand use RSocket::Send() and RSocket::RecvOneOrMore() toexchange data with the remote peer.// RSocketServ, RConnection et al.

(link to esock.lib)#include <es_sock.h>// KAfInet et al (link to insock.lib)#include <in_sock.h>void TCPSendReceiveL(){// Open socket server sessionRSocketServ ss;CleanupClosePushL(ss);User::LeaveIfError(ss.Connect());// Open connection on the socket server sessionRConnection conn;CleanupClosePushL(conn);User::LeaveIfError(conn.Open(ss));// Start the default connectionNETWORKING143TRequestStatus status;conn.Start(status);// Wait for the connection to startUser::WaitForRequest(status);// Check if Start succeedUser::LeaveIfError(status.Int());// Open TCP socket on the started connectionRSocket sock;CleanupClosePushL(sock);User::LeaveIfError(sock.Open(ss, KAfInet, KSockStream, KProtocolInetTcp, conn));// Connect to the remote peer (symbian.com)TInetAddr remoteAddr(INET_ADDR(81, 89, 143, 203), 80);sock.Connect(remoteAddr, status);User::WaitForRequest(status);User::LeaveIfError(status.Int());// Now that we are connected,// exchange some data...// Make a HTTP GET request to the remote peer_LIT8(KHTTPGetRequest, "GET / HTTP/1.0\r\nhost: www.symbian.com\r\n\r\n");sock.Write(KHTTPGetRequest(), status);User::WaitForRequest(status);// Did we manage to queue the data?User::LeaveIfError(status.Int());// Request made, now read the responseRBuf8 response;response.CreateL(512);response.CleanupClosePushL();TSockXfrLength len;sock.RecvOneOrMore(response, 0, status, len);User::WaitForRequest(status);// Did read fail or the remote peer closed the// connection?User::LeaveIfError(status.Int());// Check the length of the data receivedTInt lenRecv = response.Length();// Shutdown the socket.// Discard any pending read/writesock.Shutdown(RSocket::EImmediate, status);User::WaitForRequest(status);// Close the response buffer,// socket, connection and socket server sessionCleanupStack::PopAndDestroy(4);}Discussion: The above code snippet demonstrates usage of a TCP socketto send and receive some data.

Even though it is a simple example, it stilldemonstrates how the vast majority of applications will use TCP sockets.144SYMBIAN C++ RECIPESThis code starts a network connection with the system default settings.On the S60 platform, the standard behavior is to display a dialog withthe list of IAPs available and let the user select one. On UIQ, callingRConnection::Start() without a parameter will start the preferredIAP, if there is one – which is defined through the Internet accountsettings in the control panel. As a result, an IAP list dialog may not bedisplayed.The TInetAddr class encapsulates an IP4 or IP6 address and anyapplication using IP-based sockets, whether it is TCP or UDP, will usethis class to specify an address and port for the endpoint to connect to.We use RSocket::RecvOneOrMore() to receive data from theremote peer; unlike RSocket::Read() and RSocket::Recv(),which wait to return till the buffer (i.e., descriptor) has been filled to itsMaxLength() and can potentially be confusing, RSocket::RecvOneOrMore() returns whenever there is some data to be read from the TCPstack’s receive queue.

The length of the data received can be identifiedby checking the TSockXfrLength parameter or the length of the buffer;in the case of TCP, both are always the same. The RecvXyz()/Read()methods complete with KErrEof if the remote peer disconnectedor the socket was shut down with TShutdown::EStopInput (seebelow).RSocket::Close() ensures that all data that is queued for sending/receiving is processed first.

This might create a problem in certaincases, because a seemingly harmless call to Close() can block thethread as it completes normal disconnection. The RSocket class provides two ways to mitigate this issue. The first method, Shutdown(),asynchronously disconnects the TCP connection. Shutdown() takes aparameter of type TShutdown which directs how the TCP disconnectiontakes place. The second method is to set the TCP linger option usingTSoTcpLingerOpt (defined in in6_opt.h) on the socket before itis closed. In fact, the Symbian OS implementation of the TCP/IP stacksupports a comprehensive range of configuration options as found inother platforms.

See code sample for download accompanying this bookto see how socket/protocol-level options are specified.Tip: Always ensure that the buffer passed in the RecvXyz()/Read()methods is ample and tailored to your protocol. Otherwise you willend up calling the receive methods multiple times to get data,which is inefficient. Also, it is a common mistake to assume thatthe Send()/Write() methods complete when the data has beendelivered to the remote endpoint. In reality, they return after data isqueued in the TCP/IP stack’s internal buffer.NETWORKING4.3.5.2145Force a Connection to Use a Specific BearerAmount of time required: 15 minutesLocation of example code: \Networking\StartConnectionWithPrefsRequired library(s): esock.lib, commdb.libRequired header file(s): es_sock.h, commdbconnpref.hRequired platform security capability(s): NetworkServicesProblem: You want to force a connection to use a particular bearer.Solution: Use TCommDbConnPref to specify a bearer selection preference for RConnection::Start().#include <es_sock.h> // RSocketServ, RConnection (link to esock.lib)#include <commdbconnpref.h> // TCommDbConnPref (link to commdb.lib)void StartConnectionWithPrefsL(){// Open socket server sessionRSocketServ ss;CleanupClosePushL(ss);User::LeaveIfError(ss.Connect());// Open connection on the socket server sessionRConnection conn;CleanupClosePushL(conn);User::LeaveIfError(conn.Open(ss));// Define the selection preferences.

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

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

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

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