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

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

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

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

This is good practice in any callbackinterface – always identify the source of the callback, so that a singleprocessing function can handle multiple objects without having to haveits own way to track the ownership.Now let’s take a look inside the implementations of CSocketFountain and CSocket.CSocketFountainHere’s the main methods for CSocketFountain:class CSocketFountain : public CActive{public:static CSocketFountain* NewL();static CSocketFountain* NewL(MIncomingConnection& aCallBack);static CSocketFountain* NewL(RSocketServ& aSS);void SetConnectionCallBack(MIncomingConnection& aClient);void Listen(TUint addrFamily, TUint aSockType, TUint aProtocol,TSockAddr& aAddr);58AN INTRODUCTION TO ESOCKvoid StopListening();...};We’ve provided several overrides for NewL() to allow various combinations of external state to be provided.

If nothing is supplied thenCSocketFountain creates its own connection to ESOCK, but it is moreefficient to share a RSocketServ instance between all the objects in athread, so an RSocketServ connection can be passed in.We have also allowed for the callback destination to be changed afterconstruction. This is a useful technique, as it allows flexibility for theuser in construction order (if the eventual destination isn’t constructedbefore the CSocketFountain), and also for the callback to change asthe program’s state changes.The heart of the API is the Listen() call, which calls ListenL():void CSocketFountain::ListenL(TUint addrFamily, TUint aSockType,TUint aProtocol, TSockAddr& aAddr){iClosing = EFalse;User::LeaveIfError(iListenSock.Open(iSS, addrFamily, aSockType,aProtocol));// Now start listeningUser::LeaveIfError(iListenSock.Bind(aAddr));User::LeaveIfError(iListenSock.Listen(4)); // Q of 4IssueAcceptL();}This is surprisingly simple – first we use the Open() call, then I callBind(), then Listen() to set the local listening address and startlistening.

Finally IssueAcceptL() is called to get the first incomingconnection. This is broken out as a separate function as it will alsobe called from the RunL() each time an accept completes, to receiveanother incoming connection.IssueAcceptL() checks to see if the fountain is closing down, andif not calls RSocket::Accept() passing a new blank socket.Finally, the RunL() calls back to the fountain’s owner and issuesanother Accept() call.

All the error handling for the CSocketFountain is done through a RunError() function, which allows the RunLto leave if there are any problems. The error handling is fairly simple – theerror is reported to the client, and the listening socket closed. The fountaincan be reused by calling Listen() again.Now let’s look at the outbound half of the equation – CSocket andactive connections.3.2.2CSocket Active ConnectionsCSocket active connections are started through the Connect() call.INTO PRACTICE59EXPORT_C TInt CSocket::Connect(TUint addrFamily, TUint aSockType,TUint aProtocol, TSockAddr& aDest){// Open the socketTInt err = KErrNone;if(iUseConn){err = iSock.Open(iSS, addrFamily, aSockType, aProtocol, *iConn);}else if(iUseSubConn){err = iSock.Open(iSS, addrFamily, aSockType, aProtocol, iSubConn);}else{err = iSock.Open(iSS, addrFamily, aSockType, aProtocol);}if(err == KErrNone){// Now start the connectioniSock.Connect(aDest, iStatus);SetActive();}return err;}This starts with some logic to open the socket in the right waydepending on whether a connection or subconnection was suppliedwhen the object was created, and then calls RSocket::Connect()with the supplied address.

When the connection completes, CSocket’sRunL() will be called, which simply calls back to the owner to informthem. At this point the CSocket is ready for sending and receiving.Sending and receivingSending data is relatively simple – a buffer is passed in to CSocket::Send() which then calls RSocket::Send(). When the send completes, a callback occurs through MCSocketCallback::WriteComplete(). This is done through the CSocketWriter class, whichis a small active object used to handle the asynchronous Send(). Aswe mentioned previously, be aware that Send() completing only meansthat the data has been copied to the protocol’s internal buffers, not thatit’s actually been sent! The callback also signifies that the client is freeto modify the data in the descriptor passed to the Send() call – whilstthe Send() call is in progress the contents of the decriptor must remainuntouched, as the protocol may access it at any time.One problem with communications and active objects is the scheduling between the sender and receiver active objects.

Ideally we’d wantthem to each have about half the time, and for neither of them to be60AN INTRODUCTION TO ESOCKstarved if there’s a lot of data moving in or out. However, if two activeobjects at the same priority are ready to run then the active scheduler willalways schedule the one that was added to the scheduler first. This caneasily result in starvation. The solution used here is to remove the CSocketWriter (and CSocketReader) from the active scheduler each timethe RunL() fires, and then re-add it. This has the effect of moving theactive object to the back of the queue and thus allowing the other one torun, even if the next call completes immediately.Receiving data is slightly more complicated due to the differences insemantics for Recv() and RecvOneOrMore() between stream anddatagram protocols.

The approach used here is to always provideRecvOneOrMore() semantics for stream sockets since this is almostalways what is wanted. For datagram sockets the code additionallyprevents data loss from passing a too-small buffer by passing the KSockReadContinuation flag to the Recv() call.

The side effect of this isthat datagram boundaries may be lost if the buffer provided is smallerthan the incoming datagrams, but in general this approach works well.KSockReadContinuationHere’s a practical example of the KSockReadContinuation flagwe discussed earlier. With a datagram protocol, the RSocket receivecalls return a whole datagram at a time. If the buffer provided is smallerthan the amount of data in the datagram, the excess is silently dropped.If that’s not the behavior we want, then the KSockReadContinuation flag can be passed to the Recv() call. This instructs ESOCKto hold onto any overflow, and return it in the next call to Recv(). Ifthe Recv() call provided a TSockXfrLength parameter then this isused to indicate the length of the remaining data.Here’s an example where the remote device sends a 250-bytedatagram:TBuf8<100> iBuf;...sock.Recv(iBuf, KSockReadContinuation, iStatus, iXfrLen);// completes w/ KErrNone, iBuf contains bytes 0-99, iXfrLen 150(remainder of first datagram)...sock.Recv(iBuf, KSockReadContinuation, iStatus, iXfrLen);// completes w/ KErrNone, iBuf contains bytes 100-199, iXfrLen 50(50 bytes remaining in first datagram)...As with the CSocketWriter class, the RunL() dequeues andrequeues the active object to ensure fair scheduling.INTO PRACTICE61BufferingWhile the code presented here doesn’t provide any buffering strategy, it’ssomething that’s worth thinking about carefully for your application as itcan have a major impact on performance.First some background.

Communications links have four fundamentalperformance measures: bandwidth, latency, jitter and loss. Bandwidthis the amount of data per unit time (e.g., 10 Mb/s). Latency is the timetaken for the data to transit the network from sender to receiver (e.g., aswe write this, the time for a packet to reach www.google.com from themachine is approximately 15 ms).

Jitter is the variation in packet arrivaltimes given a constant transmission rate, i.e., the variance in latency. Loss(or packet loss) is the number of packets sent that don’t make it to thereceiver (often expressed as a percentage).These four quantities are interrelated. The available bandwidth putsa lower limit on latency – if you have 2400 bits/s bandwidth then theminimum latency for a single bit is 1/2400 s or 0.4 ms. Jitter can besmoothed by buffering, but this increases latency as packets wait in thebuffers. And packet loss impacts bandwidth, jitter and latency.In applications that perform some ‘real-time’ service it is latency orjitter rather than absolute bandwidth that is important. For example, a carcarrying 100 DVDs between two points one hour apart has a bandwidthof 400 GB/hour or 113 MB/s (∼ 1 Gb/s) but with a latency of onehour, which would make for a very painful user experience for anythinginteractive, while being ideal for non-real-time services like transferringsoftware.For your specific application, you’ll need to make design choices totrade-off these four factors to get the performance you need.

The first andsimplest choice is packet loss. If you can tolerate high jitter and latencybut not losing a single bit, then selecting a reliable transport (e.g., TCP)will give this. In some cases, rather than selecting a different transportprotocol, you might just configure it in a different way, e.g., L2CAP canbe configured to provide a reliable transport (the default), or to discarddata if it hasn’t been transmitted within a certain period.For jitter, adding buffering at the receiver will smooth out the flow ofdata, which is useful for any process that wants to consume data at afixed rate (e.g., media playback).

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

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

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

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