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

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

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

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

If not,then the application will need to handle the error, either by retryingthe connection or providing an error to the user. If your code retriesthe connection, it should only do so a limited number of times – it maybe impossible to make the connection for a wide variety of reasonsdepending on the protocol.OVERVIEW OF ESOCK35Table 3.2 Protocol detailsFlagBitmaskMeaningKSIConnectionLess0x00000001 The protocol is connectionlessKSIReliable0x00000002 The protocol is reliableKSIInOrder0x00000004 The protocol guarantees in-order deliveryKSIMessageBased0x00000008 The protocol is message basedKSIDatagram0x00000008 The same as message basedKSIStreamBased0x00000010 The protocol is stream basedKSIPseudoStream0x00000020 The protocol supports a stream-like interfacebut maintains datagram boundariesKSIUrgentData0x00000040 The protocol offers an expedited data serviceKSIConnectData0x00000080 The protocol can send user data on aconnection requestKSIDisconnectData0x00000100 The protocol can send user data on adisconnect requestKSIBroadcast0x00000200 The protocol supports broadcast addressesKSIMultiPoint0x00000400 The protocol supports point to multi-pointconnectionsKSIQOS0x00000800 The protocol supports a quality of servicemetric.

This isn’t so useful, see theRSubConnectionAPI insteadKSIWriteOnly0x00001000 The protocol is write onlyKSIReadOnly0x00002000 The protocol is read onlyKSIGracefulClose0x00004000 The protocol supports graceful closeKSICanReconnect0x00008000 The same socket can be reconnected if itdisconnects (for whatever reason)KSIPeekData0x00010000 Protocol supports peeking (looking at thedata without removing it from the protocol)KSIRequiresOwnerInfo 0x00020000 Protocol is to be informed of the identity ofthe client (i.e., process ID, thread ID andUID) of each SAP (i.e., socket serviceprovider) created36AN INTRODUCTION TO ESOCKIf the connect is taking too long, or the user changes their mind, thenan ongoing connection can be cancelled using the RSocket::CancelConnect() call.

Note that if a connection is cancelled, the socket canbe reused (and Connect() called again) only if the protocol supportsreconnection (KSICanReconnect). Otherwise the socket is put into anerror state and all operations will return errors. At this point all that canbe done is to call RSocket::Close().Passive connections Accepting incoming connections from a peer isslightly more complex than making an active connection. It involvesthree API calls: Bind(), Listen() and Accept() and two sockets.Here’s the details of the three calls:TIntTIntvoidvoidBind(TSockAddr& anAddr);SetLocalPort(TInt aPort);Accept(RSocket& aBlankSocket,TRequestStatus& aStatus);Accept(RSocket& aBlankSocket,TDes8& aConnectData,TRequestStatus& aStatus);TInt Listen(TUint qSize);TInt Listen(TUint qSize,const TDesC8& aConnectData);The first socket is the listening socket, which is bound to the addresson which you want to listen for incoming connections using Bind().Then you call Listen() on the bound socket to start the protocolstack listening for incoming connections.

Finally Accept() is called onthe listening socket, passing the second, blank, socket (see ‘Opening asocket’ for how to create a blank socket). When a connection from apeer is received, the accept call completes and the blank socket is nowconnected and ready for data transmission. You can then call Accept()again with another blank socket to receive the next incoming connection.class CSocketListener : public CActive{public:...void ListenL();virtual void RunL();...private:RSocketServ iSs;RSocket iListening;RSocket iAccept;}void CSocketListener::ListenL(){User::LeaveIfError(iSs.Connect());User::LeaveIfError(iListening.Open(ss, KAfInet, KSockStream,KProtocolInetTcp));// addr is setup with the right address somewhere elseUser::LeaveIfError(listening.Bind(addr));OVERVIEW OF ESOCK37User::LeaveIfError(listening.Listen(4));User::LeaveIfError(accept.Open(ss));listening.Accept(accept, stat);SetActive();}// Q up to four incoming//connections// Create a blank socketvoid CSocketListener::RunL(){if(stat.Int() == KErrNone){// Socket is now connected}}The queue size parameter to Listen() allows the protocol stackto queue up a number of incoming connections while it waits for theprogram to call Accept().

If the queue length is exceeded, then furtherconnections are automatically rejected by the protocol stack. For mostprograms, where the expected rate at which incoming connections arriveis much lower than the rate at which the program can Accept() eachconnection, then a queue size of four is plenty. For an application like aweb server where there might be many clients connecting simultaneouslyit may be necessary to increase this.As an alternative to the Bind() call, SetLocalPort() can beused for setting up the address if only a port number is needed, e.g.,for protocols such as TCP and UDP where a device can have multipleinterfaces and the program wants to listen on all of these interfaces. SeeChapter 6 for more details on TCP/IP, as well as details of how to listenonly on specific interfaces.As with active connections, if the protocol supports connection datathen the Listen() and Accept() calls can be used to send and receivethis data respectively.

Again, this is rarely used.Remember when you no longer want to receive incoming connectionsdon’t just stop calling Accept(), but close the listening socket usingRSocket::Close(). This frees the listening address for use by otherprograms.Sending data Once a socket has been opened and connected (forconnection-oriented protocols), it can be used for sending and receivingdata. To send data, there are several calls:void Send(const TDesC8& aDesc,TUint someFlags, TRequestStatus& aStatus);void Send(const TDesC8& aDesc,TUint someFlags, TRequestStatus& aStatus,TSockXfrLength& aLen);void SendTo(const TDesC8& aDesc, TSockAddr& anAddr, TUint flags,TRequestStatus& aStatus);void SendTo(const TDesC8& aDesc, TSockAddr& anAddr, TUint flags,TRequestStatus& aStatus, TSockXfrLength& aLen);void CancelSend();38AN INTRODUCTION TO ESOCKvoid Write(const TDesC8& aDesc, TRequestStatus& aStatus);void CancelWrite();All these calls result in a call to the protocol to send data out ontothe link.

Send() can only be used with a connected socket (i.e.,Connect() has been called successfully). SendTo() can only be usedwith connectionless sockets (see ‘Types of protocols’) as it provides theaddress of the remote peer to send the data to.So when should you use each of these?• Use SendTo() for connectionless sockets where there isn’t a fixedremote address to send the data to.• Use Send() if you need to pass flags to the send call, or to find outhow much data has actually been sent.

The length of the sent data willalways be the same as the length of the data sent unless non-blockingI/O has been set,1 in which case the send call will send what it canwithout blocking and then complete immediately.• Use Write() for stream sockets where you don’t need flags or toknow how much data was sent.The aDesc parameter is the data to be sent. This is an 8-bit descriptoras all protocols send byte streams rather than 16-bit UCS-2 data. Theflags passed to Send() are protocol-specific, apart from KSockUrgentWrite.

This flag can be used to mark the data for expedited sending,if the protocol supports urgent data (i.e., KSIUrgentData is set in theservice information).There are some other considerations when sending data which youshould take into account:1.Only one sending operation can be in progress at a time on a singleRSocket, so you must wait for a Send/SendTo/Write to completebefore calling any send operation again.2.All send operations buffer the outbound data, so the data may nothave actually been sent to the remote end by the time the call returns.1‘Blocking’ and ‘non-blocking’ I/O are something of a misnomer here – they refer tothe operation that you’ve requested, rather than the state of your thread – i.e., a blockedoperation will signal your TRequestStatus when the operation has completed.

A nonblocking operation will complete the moment that a potentially long-running operationneeds to take place with KErrWouldBlock. This confusion, unfortunately, arises from tryingto layer blocking and non-blocking I/O (required to support stdlib) on top of asynchronousI/O (used in the rest of Symbian OS).Our advice is to avoid the whole area of blocking and non-blocking I/O unless you’reporting software that needs to use it – by default sockets behave as you would expect themto, i.e., they complete your TRequestStatus when the operation has completed.OVERVIEW OF ESOCK39Of course, even if it has been there’s no way to tell if the remote endhas received it yet, so this isn’t really a problem in practice.23.

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

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

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

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