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

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

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

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

The first argument ofGetByName() is the server name you want translated. The results of thelookup are put in nameEntry upon return. When you assign nameEntry().iAddr to a TInetAddr, you’ll set the IP address associated withthe server name, then you just need to set the port (port 80 in our casefor HTTP).You can now set up the destination address that you will use to connectto the server:TInetAddr destAddr;destAddr = nameEntry().iAddr;destAddr.SetPort(80);// Set address to DNS returned IP address// Set to well-known HTTP portConnection to the remote serverThe RSocket Connect() is used to establish a connection with theremote web server:sock.Connect(destAddr,status);User::WaitForRequest(status);if (status != KErrNone){_LIT(KSocketConnectFail,"Failed to connect to server");HandleError(KSocketConnectFail,SockServ);return res;}Sending a packetOnce the socket is created and connected, packets can be sent (remember,a connection is not required in the case of UDP).

RSocket provides theSend() method to send data through the socket. Send() has thefollowing form:void Send(const TDesC8& aBuffer, TUint aFlags, TRequestStatus& aStatus)340SYMBIAN OS TCP/IP NETWORK PROGRAMMINGThe buffer to send is specified as an 8-bit descriptor, and all bytes in thedescriptor are sent through the socket.The HTTP GET command in our example is sent to the web server asfollows:TBuf8<300> getBuff;getBuff.Copy(_L8("GET "));getBuff.Append(aDoc);getBuff.Append(_L("\xD\xA"));// Send HTTP GETsock.Send(getBuff,0,status);User::WaitForRequest(status);RSocket also has a SendTo() method that is used to send UDP data.This method has the same form as Send(), except an extra argument isadded to specify the remote address that the packet should go to.

Thefollowing code shows a way of sending data via UDP using SendTo().Note that I have omitted error checking for simplicity.RSocket sock;RSocketSrv sockSrv;sockSrv.Connect();sock.Open(socksvr,KafInet,KSockDatagram,0);TInetAddr destAddr;destAddr.SetAddr(INET_ADDR(10,1,2,3);destAddr.SetPort(80);TBuf8<300> buff;buff.Copy(_L("Some stuff to send over UDP"));sock.SendTo(buff,destAddr,0,iStatus);User::WaitForRequest(iStatus);You can also use Send() to send UDP data, provided you firstcall Connect(), to connect to the remote address.

Connect() is aconvenience method for UDP, you call it so that the remote address neednot be specified every time you send a UDP packet.Receiving packetsThe web page is retrieved in our HTTP example as follows:TBuf8<200> buff;do{TSockXfrLength len;sock.RecvOneOrMore(buff,0,status,len);User::WaitForRequest(status);PrintOutput(buff); // some generic 8-bit output-to screen or file} while (status == KErrNone);SYMBIAN OS SOCKET API341The example uses the RSocket::RecvOneOrMore() method toretrieve the data sent from the server.

RecvOneOrMore() has thefollowing form:void RecvOneOrMore(TDes8& aDesc, TUint aFlags, TRequestStatus& aStatus,TSockXfrLength& aLen)RecvOneOrMore() acts like the BSD recv() socket call in that itcompletes when any data is available from the connection. The receivebuffer (aDesc) is specified as an 8-bit descriptor and the received data isadded to this buffer. The size of the descriptor is updated to match thenumber of bytes received (aLen also returns the number of bytes thatwere received).There is another RSocket method to receive data, called Recv().You may be tempted to use Recv() instead of RecvOneOrMore()due to the name matching the BSD recv() call. However, there isa big difference between these receive calls when using TCP.

UnlikeRecvOneOrMore(), which completes when any amount of data isreceived, Recv() will not complete until the entire descriptor (specifiedby the maximum length of the receive descriptor) is filled with data.So, unless you know exactly how many bytes you will receive from theserver, do not use Recv() for TCP.Recv() is usually used for UDP. It behaves differently for UDP in thatRecv() returns the data from a received UDP datagram even if it is belowthe maximum length of the descriptor (bear in mind that the Recv()method can only be used for UDP if Connect() was called first). So,Recv() acts the same for UDP as RecvOneOrMore() does for TCP.RSocket also provides a method called RecvFrom() for receivingUDP data. This method is equivalent to the BSD recvfrom() function.It receives a UDP packet and also the address of the host that sent it.RecvFrom() has the following form:void RecvFrom(TDes8& aDesc, TSockAddr& anAddr, TUint aFlags,TRequestStatus& aStatus)This function receives UDP data and supplies not only the data receivedbut also the address of the endpoint that sent the data.

TSockAddr isthe base class for TInetAddr, so a TInetAddr can be passed here toobtain the sending node’s address.Closing the socket and socket serverThe example cleans up the socket and socket server connection with:sock.Close();sockSrv.Close();342SYMBIAN OS TCP/IP NETWORK PROGRAMMING11.3.3 Network Programming Using Active ObjectsAs you’ve seen, I used User::WaitForRequest() to wait for theasynchronous socket functions to complete in the previous section.However, a better way to call these socket functions is within activeobjects, which were discussed in Chapter 8. The active object frameworkallows the system to handle events, such as those arising from userinput, while the socket functions are active.

When they complete, theassociated active object’s RunL() method handles events as appropriate.So the Connect() call, for example, could look something like:void CMyActiveObject::DoNetworkStuff(){iSock.Connect(destAddr,iStatus);SetActive();}void CMyActiveObject::RunL(){// Invoked when the asynchronous function Connect() completes.// iStatus contains the completion status}Although you may want to refine how errors and completions arehandled by the calling program (for example, having the calling programpass callbacks for its own handlers); this would vary depending on whatyour software does and how it would be used.With active objects, you can have your program continue to processother, non-network, events while your network communication is takingplace.

For example, if you invoke networking functionality in a GUIapplication using an active object – say in response to some user selection – your GUI program can continue to process other user events whilethe network communication is in progress.Normally you will want to have a sequence of networking callsperformed in the background, started by a single active object method(e.g., a connect, followed by a send, followed by one or more receives).To do this, you create a simple state machine in an active object, includinga method that makes the first network call in the sequence (e.g., resolvingthe host name). Then your RunL() method would invoke the rest of thenetwork calls, in response to completion events from previous networkactivity.For the example of loading a web page, an active object can bedeclared as follows:class CWebPage : public CActive{public:static CWebPage* NewL();~CWebPage();void OutputWebPage(const TDesC& aServ, const TDesC& aDoc);enum TLoadStateSYMBIAN OS SOCKET API343{EResolvingName,EConnecting,ESending,EReceiving};protected:void RunL();void DoCancel();CWebPage();void ConstructL();private:TLoadState iState;TBuf8<100> iUrlDoc;RSocketServ iSocketSrv;RSocket iSocket;TNameEntry iNameEntry;RHostResolver iResolver;TBuf8<20000> iWebBuff;TSockXfrLength iLen;};The OutputWebPage() method would initialize the socket and startthe first asynchronous function in the sequence (resolving the host name)as follows:void CWebPage::OutputWebPage(const TDesC& aServerName, const TDesC& aDoc){TInt res = iSocketSrv.Connect();if (res != KErrNone){_LIT(KSockOpenFail,"Socket server connect error");HandleError(KSockOpenFail);return;}iUrlDoc.Copy(aDoc);// Resolve name, rest handled by RunL()iState=EResolvingName;res =iSocket.Open(iSocketSrv,KAfInet,KSockStream,KProtocolInetTcp);if (res != KErrNone){_LIT(KSockOpenFail,"Socket open failed");HandleError(KSockOpenFail);return;}res = iResolver.Open(iSocketSrv, KAfInet, KProtocolInetTcp);if (res != KErrNone){_LIT(KResvOpenFail,"host resolver open failed");HandleError(KResvOpenFail);return;}iResolver.GetByName(aServerName, iNameEntry, iStatus);SetActive();// first asyncronous function started, RunL() takes over from here.}344SYMBIAN OS TCP/IP NETWORK PROGRAMMINGThe active object RunL() can then be implemented to process theevent and start the next socket call in the sequence, based on the statevalue in iState, as shown below:void CWebPage::RunL(){if ( (iStatus != KErrNone) && (iStatus != KErrEof) ){// error, abort sequence, no further RunL()s will be invoked_LIT(KWebPageFail,"Error loading web page");HandleError(KWebPageFail);} else{// walk through state machine to load the web page.switch(iState){case EResolvingName:{TInetAddr destAddr;destAddr=iNameEntry().iAddr;destAddr.SetPort(80);// Connect to the remote hostiState=EConnecting;iSocket.Connect(destAddr,iStatus);SetActive();break;}case EConnecting:{// Send GET packetTBuf8<300> getBuff;_LIT8(KGetCommand, "GET ");getBuff.Copy(KGetCommand);getBuff.Append(iUrlDoc);_LIT(KCRLF,"\xD\xA");getBuff.Append(KCRLF);iState=ESending;iSocket.Send(getBuff,0,iStatus);SetActive();break;}case ESending:{// Start receiving web page nowiState=EReceiving;iSocket.RecvOneOrMore(iWebBuff,0,iStatus,iLen);SetActive();break;}case EReceiving:if (iStatus != KErrEof){// Web data receivedWriteTextOutput(iWebBuff); // write data to// console or file, whatever.iSocket.RecvOneOrMore(iWebBuff,0,iStatus,iLen);EXAMPLE: RETRIEVING WEATHER INFORMATION345SetActive();} else{// End of file, page load completeiSocket.Close();iResolver.Close();iSocketServ.Close();}break;default:ASSERT(EFalse); // Should never get here}}}iState uses an enumeration to indicate what the active object’s RunL()should do next in response to a completion event.

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

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

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

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