Главная » Просмотр файлов » Symbian OS Communications

Symbian OS Communications (779884), страница 12

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

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

Attach() can be called to bindyour RConnection object to one of the connections you’ve discovered.Note that the EnumerateConnections() and Attach() operationsare mainly useful for programs that display the current state of all connections to the user. Most programs should call Start() and let thenormal selection process take place, even if asking for a specific IAP.This makes the code for starting a connection much simpler, as it doesn’tmatter whether the connection is started or not.

In the case where thedesired connection already exists, ESOCK and the rest of the frameworkwill internally perform an Attach() for you.The aConnectionInfo parameter to GetConnectionInfo() andAttach() is specified as a TDesC8&, but in fact the informationreturned is a TPckgBuf<TConnectionInfoV2>.Now that your RConnection is associated with an active bearer,either through starting the bearer or via Attach(), you can retrievevarious items of information about the connection.TIntTIntTIntTIntTIntGetIntSetting(const TDesC& aSettingName, TUint32& aValue);GetBoolSetting(const TDesC& aSettingName, TBool& aValue);GetDesSetting(const TDesC& aSettingName, TDes8& aValue);GetDesSetting(const TDesC& aSettingName, TDes16& aValue);GetLongDesSetting(const TDesC& aSettingName, TDes& aValue);TInt Name(TName& aName);The Get.

. .() calls return information about the connection. Name()returns a name for the connection that can be used to bind otherRConnection instances to the same connection using RConnection::Open(RSocketServ&, TName&aName).OVERVIEW OF ESOCK49To allow programs to monitor the data flowing over a connection,there are various methods: DataTransferredRequest(), DataSentNotificationRequest() and DataReceivedNotificationRequest(). There’s more information in Chapter 6 on these methods, or check out the documentation in the Symbian OS Library fordetails on how to use these.One final oddity of RConnection: unlike nearly all R-classes inSymbian OS, it can’t be bitwise-copied using ‘=’. If you want to share anRConnection handle, you’ll need a reference or pointer.Subconnections Within the Symbian OS connection model, eachRConnection can have multiple subconnections associated with it.A subconnection is used to configure the quality of service for socketsbound to the subconnection.

This allows a single bearer to supportdifferent services with individual QoS requirements. For example anHSDPA packet data connection might have a VoIP session, a multiplayergame and a video download all occurring at the same time. Each service has specific QoS requirements: VoIP needs a guaranteed minimumbandwidth and low latency; the game needs low latency and the videodownload wants maximum bandwidth on a best-effort basis. By using thesubconnection APIs, it is possible to associate each application’s trafficwith a separate PDP context with the required QoS negotiated and agreedwith the network (again, see Chapter 6 for full details).Most of the control of subconnections is done through the RSubConnection class (see below), but for historical reasons the RConnectionclass provides a basic ability to enumerate and query its subconnections.TInt EnumerateSubConnections(TUint& aCount);TInt GetSubConnectionInfo(TDes8& aSubConnectionInfo);TInt GetSubConnectionInfo(TUint aIndex, TDes8& aSubConnectionInfo)These functions work similarly to the connection enumeration functions.

The descriptor parameter needs to be a packaged TSubConnectionInfo, created using TPckgBuf<TSubConnectionInfo> orTPckg<TSubConnectionInfo> . This API only provides very minimal information on a subconnection – use the RSubConnection::GetParameters() call to get more useful information.For IP-based connections, the methods on RConnection and RSubConnection internally use different methods for gathering the information. As such it’s possible that the RConnection values returned donot reflect the true number of subconnections.

This will be addressedin future releases, but for now there is no reliable way to enumerateavailable subconnections. However, this shouldn’t be a problem for mostapplications.50AN INTRODUCTION TO ESOCKRSubConnectionRSubConnection provides the management interface to subconnections, allowing QoS parameters to be negotiated. There’s more information on this in Chapter 6 and in the Symbian OS Library, so we won’t gointo the details here.3.1.6 Naming and Lookup ServicesWe’ve looked at ESOCK’s facilities for data transfer (RSocket) and connection management (RConnection), but there’s one more challengethat ESOCK helps us overcome.

That is figuring out how to contact theremote system we’re interested in.In all networks, devices (or more accurately interfaces) are identifiedby an address. Usually this is simply a number: for example the Ethernetadaptor on the computer I’m writing this on has the address 00-11-85-8893-C5 (in hexadecimal), while the IP address is 10.18.212.1. Similarly, myBluetooth hardware has an address of 00-0F-B3-4E-04-15. While numberswork fine for computers, they are distinctly unfriendly for humans.As a result most types of network provide a human-readable namethat can be translated to give the numerical address. The most common example is, of course, DNS names in IP networks, such aswww.symbian.com, but other networks behave similarly.

For example,Bluetooth provides a device name, such as ‘Malcolm’s P910’, for eachdevice. The major exception to this is infrared where the device to communicate with is usually identified by physical proximity. Device namesare still available, but mainly used after a connection has taken place toindicate to the user the name of the device that has connected.3Once the name has been resolved, the next challenge is to makeconnection with the right service. A single device can provide multipledifferent services: for example, a computer providing web, FTP, emailand file-sharing services; or a phone providing file transfer and modemservices.

Each service appears on a different port which the client canconnect to. In some systems, notably TCP/IP, the ports are well-known,fixed numbers e.g., HTTP on port 80, SMTP on port 25. In others, suchas Bluetooth and IrDA, the port number is not necessarily fixed – remotedevices support a service discovery database from which you can retrievethe necessary information required to create the connection.ESOCK handles this address resolution and service discovery processthrough two classes, RHostResolver and RNetDatabase. There’s3At this point we should note that device names provide no authentication of theremote machine.

This should be obvious – anyone can set their Bluetooth device name to‘Malcolm’s P910’. Even with DNS, it is possible to insert incorrect information into thesystem (search on the Internet for ‘DNS cache poisoning’ for an example of this). As a result,if you need to ensure that you really are communicating with the correct device, you needto use one of the security mechanisms described in the individual technology chapters, forexample, TLS for IP networks, Bluetooth link authentication for Bluetooth.OVERVIEW OF ESOCK51another class confusingly called RServiceResolver which is obsoleteand is not implemented by any protocol delivered by Symbian as part ofSymbian OS.

Some technologies provide wrappers over the RSocket,RHostResolver or RNetDatabase APIs to make them easier to use.See individual technology chapters for details of this.RHostResolverThe RHostResolver class is at the heart of mapping names to addressesand vice versa. It provides a common interface across protocols, butsince each protocol has its own method for address resolution, thereare significant differences between the various protocol implementations.It’s therefore important to consult the relevant chapter of this book todiscover how to use this in practice.Like all the ESOCK APIs, the first order of business is to connect toESOCK:TInt Open(RSocketServ& aSocketServer,TUint anAddrFamily,TUint aProtocol);TInt Open(RSocketServ& aSocketServer,TUint anAddrFamily,TUint aProtocol,RConnection& aConnection);Host resolvers are protocol-specific, so when you connect to ESOCKyour program needs to specify which protocol you want to access. Theflags are the same as for RSocket.

You’ll also notice that there’s anoverload of Open() that takes a RConnection parameter. In this caseany communication that the protocol needs to do to satisfy requests willflow over the specified RConnection. This is necessary for examplewhen two IP bearers are open, each with their own DNS servers.void GetByName(const TDesC& aName,TNameEntry& aResult,TRequestStatus& aStatus);TInt GetByName(const TDesC& aName,TNameEntry& aResult);void Next(TNameEntry& aResult,TRequestStatus& aStatus);TInt Next(TNameEntry& aResult);The first functions provide a name to address lookup, taking a nameand returning a TNameEntry which contains the name, address andany flags.

If the protocol supports having a single name map to multipleaddresses then you can call Next() to retrieve further addresses. Next()returns KErrNotFound when there are no more addresses for the name.Not all protocols support a name to address mapping, for exampleBluetooth does not.52AN INTRODUCTION TO ESOCKvoid GetByAddress(const TSockAddr& anAddr,TNameEntry& aResult,TRequestStatus& aStatus);TInt GetByAddress(const TSockAddr& anAddr,TNameEntry& aResult);GetByAddress() performs the inverse mapping when possible – thatis it takes an address and returns a name. This method is also usedby Bluetooth to perform discovery of devices in range, but perhapsnot in the way you’d initially expect – the ‘address’ in this case is aTInquirySockAddr specifying the type of search you wish to perform.Bluetooth device addresses are returned from this search.

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

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

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

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