Главная » Просмотр файлов » Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007

Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 35

Файл №779889 Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (Symbian Books) 35 страницаWiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889) страница 352018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Any request produces a web page which shows the current status ofthe vote. In a more sophisticated web framework, the HTML code wouldprobably be generated using an external template.The client code is in Example 79. Remember to change the URL topoint at your server.Example 79: Voting clientimport sysinfo, urllib, json, appuifw, e32URL = "http://192.168.0.2:9000"imei = sysinfo.imei()def json_request(req):enc = json.write(req)return json.read(urllib.urlopen(URL, enc).read())def poll_server():global voted_alreadyres = json_request({"voter":imei})votes, winner = res["winner"]if "closed" in res:appuifw.note(u"Winner is %s with %d votes" % (winner, votes))lock.signal()return Falseelif not voted_already and "title" in res:appuifw.app.title = u"Vote: %s" % res["title"]names = []for name in res["choices"]:names.append(unicode(name))idx = appuifw.selection_list(names)if idx == None:lock.signal()return Falseelse:res = json_request({"voter":imei, "choice":names[idx]})appuifw.note(unicode(res["msg"]))voted_already = Trueprint "Waiting for final results..."else:182MOBILE NETWORKINGprint "%s has most votes (%d) currently" % (winner, votes)e32.ao_sleep(5, poll_server)return Truevoted_already = Falselock = e32.Ao_lock()print "Contacting server..."if poll_server():lock.wait()print "Bye!"The client contains two functions: json request(), which encodesa message in JSON, sends it to the server and returns the server reply thatis decoded from a JSON message.The function poll server() contains the program logic.

It starts bysending a request to the server that includes the phone’s IMEI to identifythe phone. The response from the server is assigned to the variable res.From the client’s point of view, there are three modes:• The vote is closed, in which case the server response res includes thekey ‘closed’. In this case, the program shows a popup note declaringthe winner and exits.•The vote is ongoing and the user has already cast a vote.

In this case,the current status of the vote is printed out on the console.•The vote is ongoing and the user has not cast a vote yet. In this case, aselection list is shown that presents the choices and lets the user casta vote. The choice made by the user is then sent to the server.The current mode is determined by the response message, res. If thevote is still ongoing, the e32.ao sleep() function is used to call thefunction poll server() again after a five-second interval. This way,the client receives the status of the vote from the server almost in realtime.To test this service, start the server software on your server.

Once theserver is running, you can connect to it with your web browser – theaddress can be found in the client’s URL constant. A web page shouldopen that shows the initial status of the vote. Refresh the page every nowand then to see the latest status of the vote.Then, open the client program on your phone and cast a vote for oneof the candidates. After this, you can follow progress of voting on thePyS60 interpreter console, until the voting time expires and a popup noteis shown that declares the winner. If you have several phones available,any number of phones can cast a vote, but only once per phone.PEER-TO-PEER NETWORKING1838.6 Peer-to-Peer NetworkingThe previous examples have been built on the client–server architecture:the roles of the client and the server have been distinct.

The client–serverarchitecture makes sense if the service requires a common ‘shared memory’ or some other common resource, which is maintained by the serverand accessed by the clients. In the voting example, the server maintainedthe status of voting, which can be seen as an instance of ‘shared memory’.However, think of an instant messaging service or a game of chessbetween two players. In the former case, the service has no shared stateor memory; individual messages are passed back and forth. In the lattercase, the state of the shared chess board is easily maintained by both theclients (players) separately.

These programs could work without a centralserver. The communication takes place only between individual phonesin a peer-to-peer manner (Figure 8.6).Figure 8.6 Peer-to-peer networkingThe issues related to server-side sockets on the phone also applyto peer-to-peer networking, making universal real peer-to-peer servicesdifficult to implement.

By real peer-to-peer networking we mean that thephones are able to communicate directly with each other, without help184MOBILE NETWORKINGfrom any central server. The Bluetooth chat example in Section 7.3 wasa real peer-to-peer application in this sense.Many WiFi-enabled phones support ad hoc networking. In ad hocmode, the phones form a WiFi-network among themselves without helpfrom a base station.

In ad hoc networks, real peer-to-peer communicationis possible but you have to find a way to assign IP addresses to theparticipating phones. You can use ad hoc networks in PyS60 by definingan access point in ad hoc mode in the phone’s connectivity settings andchoosing this access point for networking in PyS60.If we accept a little help from a server, peer-to-peer networkingbecomes much more feasible.

For instance, this approach is used bySkype and BitTorrent protocols. In the following discussion, we presentan approach for peer-to-peer networking with mobile phones that relieson a central server. However, this server is not application-specific.Instead, it is designed to facilitate communication between phones.Since the server, actually a gateway, is generic in nature, you canuse it to build various services in which phones communicate in apeer-to-peer manner. Note that even though Examples 80 and 81 dotheir jobs properly, probably better alternatives exist for real productionenvironments.

For example, have a look at Jabber and the XMPP protocolto see a similar and extensively field-tested, approach.8.6.1 JSON GatewayWe implement a server (actually, a gateway) that acts as a middle manbetween phones. Since the gateway runs on your PC (or on some externalserver), you need to have Python installed there as well.

Phones maysend any JSON messages to each other, by way of the gateway. With thisgateway, it is possible to implement peer-to-peer networking in PyS60.In technical terms, the gateway works as follows:•Each client maintains a persistent TCP connection to the central server.•When a client opens a new connection to the server, it registers itselfwith a unique name.•A client sends a message to the server, which includes the recipient’sregistered name.•The server pushes the message to the recipient’s open TCP connection.In Section 8.5, we listed three hindrances to building a server on thephone side.

This approach neatly solves, or evades, those issues: changingIP addresses are not an issue since addressing works by registered names,not by IP addresses; firewalls and NAT devices are not a problem,since the client always initiates the connection to the server and notother way around; the phone does not have to handle multiple socketsPEER-TO-PEER NETWORKING185simultaneously: Messages from all peers are received through a singleconnection.We implement a generic JSON message gateway over TCP. You canuse this gateway to implement various peer-to-peer applications. If youwant to get right into implementing enterprise-level, process-managementapplications, multiplayer games and collaborative art, you can skip thefollowing explanation of the internals of the gateway. However, the serveris not complex and, once you get familiar with it, you can extend it foryour own purposes easily.Conceptually, the code is simple.

It works as follows:New Connection:Register Client.Serve forever:Read message, including recipient.Client wants to close the connection? Close.Otherwise, push the message to the recipient.Unfortunately, the implementation looks a bit more intricate. This isbecause it has to handle multiple TCP connections simultaneously, in contrast to the previous example servers. Moreover, as this code implementsa generic service, instead of a single, simple application, extra attentionhas been paid to error handling compared to the previous examples.The gateway uses the following protocol for messaging: each messageis a dictionary, encoded in JSON; dictionary keys are strings; keys thathave an exclamation mark as the first character are reserved for the gateway protocol.

The application is free to use any other strings as keys forits internal communication. The following keys are used by the gateway:•!name – Register the client with this name.•!close – Close the connection.• !dst – Forward message to the named recipient.The implementation is based on the standard TCP server, but it is spicedup with SocketServer.ThreadingMixIn, which modifies the serverbehavior so that each client is handled in a separate thread of execution.The result is that multiple connections can be handled simultaneously,but we must be extra careful that the threads do not mess up each other.The gateway code is divided into two parts. You should combine themto make the final application.

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

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

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

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