Главная » Просмотр файлов » 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), страница 34

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

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

The function process get() is given two parameters: the requested path from the URL (path) and the parsed parameters(query). The actual task performed by the function depends on theexample. The function returns two values: the MIME type of the response,which tells whether the response contains, for example, HTML, plain textor an image, and the actual response in a string that is sent back to therequester.

The requester is typically a web browser.The function process json() is given the decoded JSON requestas a sole parameter. It may return any Python data structure that is thenencoded in JSON and returned to the requester. The requester is typicallya PyS60 program.Each of the following examples, which require a web server, providesits own init server(), process get() and process json()functions to handle tasks specific to that particular example.

With eachexample, you should replace these functions in the web server codeaccordingly.PUSHING DATA TO A PHONE177As with the TCP server, you can pick another port for the server insteadof the default, 9000. Once the above code is running on your server,you can try to connect to it with a web browser on your PC and onyour phone.

The address is of the form http://192.168.0.2:9000/test/,where the IP address corresponds to that of your server. If everything goeswell, the browser shows an echo message with the requested path andparameters.8.4.3 Advanced Topics in NetworkingSo far, we have focused on using the phone as a network client. Traditionally, this has been the default role for a mobile device, and the operator’sdata centers have taken care of serving information.

Technically, once amobile device has an IP address there is no reason that it could not act asa server as well. After all, a server is just one of the two equal endpointsin the TCP connection.Conceptually, reversal of the mobile device’s role from an informationconsumer to a producer is a small revolution. Information produced byyour phone is qualitatively different from a typical website.

In contrastto a web page, your phone produces information that is bound to time,location and a specific person.In the next three sections, we see how PyS60 can be used to make thephone a more active information consumer, as well as a producer for theInternet.8.5 Pushing Data to a PhoneThe socket module provided by PyS60 closely resembles its siblingon the server side.

The module contains functions for listening to aport for incoming TCP connections (functions bind(), listen() andaccept()). With these functions you can create a simple TCP serverand run it on a phone as you would do on a PC (Figure 8.5).8.5.1 Drawbacks with using a Phone as a ServerHowever, three issues tend to make life difficult for phone-based servers:•Unless the phone stays in one location all the time, its IP address islikely to change when the phone moves from one network to another.Clients must be kept updated on the mobile server’s most recent IPaddress; fortunately, this is possible with several methods.•Typically, operators do not allow inbound connections over the GSMor 3G network to the phone, because of security and other reasons.178MOBILE NETWORKINGFigure 8.5•Pushing data to a phoneEven though server-side sockets are supported by PyS60, there is onlylimited support for handling multiple simultaneous connections onthe phone side.

Thus, scaling up performance of a server-on-a-phoneis not an easy task.Within a small, local WiFi network these issues might not be issues atall. Thus, it is possible to perform local experimentation on phone-sideserver software. However, beware that this aspect of PyS60 has receivedless testing than other, more widely used modules and thus you may findsome bugs still lurking in PyS60.In such a setting, it is important to know the phone’s IP address (seeExample 77).Example 77: Phone’s IP addressimport socketap_id = socket.select_access_point()apo = socket.access_point(ap_id)apo.start()print "PHONE IP IS", apo.ip()The above three points affect all PyS60 programs that rely on externalevents that are delivered by the network, including multiplayer games,email clients and real-time chat applications.

In all these cases, anexternal entity, such as a game server, must push some information to thePUSHING DATA TO A PHONE179phone. Since listening for incoming connections on the phone is oftennot feasible, because of the above issues, it is necessary to consider otherapproaches.There are two common workarounds: the phone may poll the serverat regular intervals and check whether there is new information to beprocessed or the phone may open a TCP connection to the server andkeep it open so that the server can push information by way of thispersistent pipe back to the phone.The main problem with the former approach is that if the pollinginterval is too short, say less than a minute, continuous polling is likely todrain the phone’s battery.

The biggest issue with the latter approach is thatit does not work with HTTP. According to the current HTTP specification,HTTP requests always originate from the client, so a server running onthe phone cannot initiate the connection.8.5.2 Voting ServiceIn this section, the polling approach is demonstrated using HTTP. Thisexample implements a voting service. The server initiates a poll, whichconsists of several choices.

The phone client is allowed to set a vote toone of the choices, within a certain time period that is reserved for voting.Once the voting time has expired, a popup reports the winner on thephone screen. Progress of voting can be followed on a web page in realtime.You should combine the example below with the basic HTTP serverin Example 75 to make the full server. These lines should come afterthe main server. If you are familiar with some web framework, such asRuby on Rails or Django, you can easily re-implement the server logic inExample 78 using your favorite framework. You can use the phone clientin Example 79.Example 78: Voting serverimport time, jsondef init_server():global title, choices, already_voted, startedstarted = time.time()already_voted = {}title = u"What shall we eat?"choices = {u"Tacos": 0,\u"Pizza": 0,\u"Sushi": 0}print "Voting starts"def vote_status():voting_closed = time.time() - started > 60results = []180MOBILE NETWORKINGfor choice, count in choices.items():results.append((count, choice))return voting_closed, max(results)def process_json(query):voting_closed, winner = vote_status()if voting_closed:return {"closed": True, "winner": winner}msg = ""if "choice" in query:if query["voter"] in already_voted:msg = "You have voted already"else:choices[query["choice"]] += 1already_voted[query["voter"]] = Truemsg = "Thank you for your vote!"return {"title": title, "winner": winner,\"choices": choices, "msg": msg}def process_get(path, query):voting_closed, winner = vote_status()msg = "<html><body><h1>Vote: %s</h1><br/>" % titlefor choice, count in choices.items():msg += "<b>%s</b> %d<br/>" % (choice, count)if voting_closed:msg += "<p><h2>Voting closed.</h2></p>"msg += "<h1>The winner is: %s</h1>" % winner[1]else:msg += "<h2>%d seconds until closing</h2>" %\(60 - (time.time() - started))return "text/html", "%s</body></html>" % msginit_server()httpd = Server((’’, 9000), Handler)httpd.serve_forever()The function init server() initiates the vote.

The starting time ofthe vote is saved in the variable started. The dictionary alreadyvoted includes the IMEI from the phones which have already cast avote. The variable title gives the name of the vote and the dictionarychoices holds the candidates with the number of votes they havereceived thus far.The function vote status() is used to determine the status ofthe vote. The variable voting closed is false as long as fewer than60 seconds have elapsed since the vote started, after that, the variablebecomes true. Then, we loop over the choices dictionary to determinewho is now leading the vote.We build a list of tuples, so that the number of votes is the first item inthe tuple and the candidate name is the second item.

From this list, thestandard function max() returns the tuple in which the first item has thePUSHING DATA TO A PHONE181largest value, hence, the second item in this tuple contains the currentleader.The function process json() handles requests from the phoneclients. If the vote has already expired, the function returns immediatelyand informs the requester about this. Otherwise, if the request queryincludes the keyword ‘choice’, the client wants to cast a vote. The voteis cast only if this voter has not cast a vote before; that is, the phone IMEIdoes not exist in the dictionary already voted. The function returnsa message that contains all relevant information about the vote and itscurrent status.The function process get() handles requests from the web browser.

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

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

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

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