検索 - みる会図書館

全データから 11232件ヒットしました。

Building the Realtime User Experience


BuiIding the ReaItime User Experience

Building the Realtime User Experience


CHAPTER 6 Chat One of the most compelling aspects of creating realtime web applications is the ability [ 0 create experiences that were previously available only on the desktop. The syndica- tion example worked as a realtime experience from server [ 0 server, and the Others have largely been from server t0 user. This chapter builds on those principles t0 create a realtime user-to-user experience. ln this chapter, we re going tO explOit JavaScript and Tornad0 t0 build a fully interactive realtime chat application reminiscent 0f AOL lnstant Messenger. Before moving ontO the COde, it's important tO discuss what features a user expects tO see when he logs intO an instant messaglng application. The obvious first expectation is thatthe application will deliver the messages instantly. Second, chat sessions happen between tWO specific users; this iS not group chat. Finally, users Of modern chat appli- cations expect subtle realtime interactions, such as the ability tO see that the user on the other end of the line is typing. This application will have those features while operating in a standard web browser. Setting Up the Basic C0de The Basic HTML Frame Building this application with Tornado means we can reuse the existing directory structure frOI れ our last application. We'll store our templates in the existing tem- plates fOlder and our static JavaScript files in the 立 4 行 c directory. TO get started, open your 川 p s directory and create a file called c 厖 ト 川 4 ⅲ . 川 I. Add the following code to that file: く !DOCTYPE html> く html> く head> く tit1e>ReaItime Chat く /title> く style>. chat-content { max-height: 200PX ; overflow: auto; } く /style> く /head>

Building the Realtime User Experience


Adding this instant messaging functionality— 、 vhich opens an instantaneous C01 れ 1 れ u ー nication channel with a user, regardless Of whether they're using your site in the web browser—opens up a lOt Of doors. part Of building a truly realtime experience is allowing users tO get data in and take it out from whatever method iS most readily available. lnstant messaging provides a paradigm that is familiar tO most users and allOWS for communlcation in places not available via the standard web browser. Setting Upan API ー 151

Building the Realtime User Experience


Push (long polling) Checkfor new items Check fo 「 new items Stay connected until new data is available NO new items one new item ・ SIeep fo 「 10 seconds Stay con nected until new data is available Check fo 「 new items Check fo 「 new items TWO new items NO new items : SIeep fo 「 10 seconds Check fo 「 new items one new item : SIeep f0 「 10 seconds Check fo 「 new items 、 日 g ″ 尾 1-3. Visualizing 〃 4 訪 怩 〃 リ ″ Building a realtime user experience is language agnostic, and in this book, l've chosen tO use several different languages in the examples. Some examples use several technol- ogies chained together. If you're not familiar with one language, don't worry about it. Much Of the COde is written SO you can read it ifyou're familiar with basic programming practices, plus l've done 1 れ y best tO explain it in the text. Prerequisites ー 5

Building the Realtime User Experience


App DetaiIs Website Name• Which website will you use the AP け 0 「 ? Just fO 「 you ロ ・ ef 朝 ℃ 「 ℃ e realtimebook Website URL ④ l.e 、 http://example.com/mobile settings p : ″ the 「 ea に 給 k.com Website Description What is your website about? Examples for Building the Realtime User Experience SMS P 「 ef ⅸ を 0 FO ⅱ ncomi 四 and outgoing messages. Between 5 and 8 characters. realtime CalIback URL* 0 Where should we send incoming events? 、 http://exampleocom/incoming http://instant・ messaging.appspot.com/sms/incoming/via/zeep ( ー Cancel g 尾 & 9. R ぉ げ ⅵ れ g 4 た ル 0 ル 〃 Zeep Mo わ Of the callbacks from the service tO the same SMSIncomingHand1er controller that we created t0 handle all 0f the incoming messages. Changing the service name enables the COde tO quickly determine the source Of each request. After reserving your keyword, the Zeep Mobile website greets you with a newly created API key and secret. Keep these values handy, as we'll be using them in the code. Sending and Receiving the Messages ー 173

Building the Realtime User Experience


What ls ReaItime? Since the explosion 0f the Web, developers have been inclined t0 think in terms 0f building websites. Even in this b00k, l've spent a good deal 0f time writing about building websites. But make no mistake about it, a realtime user experience does not exist entirely inside a web browser. The original web browsers were designed t0 load and display web pages. The idea 0f a web page iS quite similar tO the printed page. lt iS a StatiC document' stored in a computer, but a static document nonetheless. The interface Of web browsers evolved t0 work within this paradigm. There is a Next button and a Back button designed to take you from the current page t0 the page that you viewed previously. That makes perfect sense when you re working with documents. However, the Web is quite quickly shifting away from a document-based paradigm t0 a web-based form 0f commumcat1011. lt used t0 be that a web page was more or less published t0 the Web. A page was created and given a specific URI, and when the user went t0 that page' it was pretty clear what to expect. Now we have sites like Faceb00k ( 印 : 〃 ル ル ル c 訪 00 た . co 川 ) where the same URL is not only different for each of the hundreds of millions of different users, but it changes moments after a user loads the page. Changinglnteractions ln the past, the interaction between a user and a web application was very simple.When a user wanted content, she would load up her browser, point it at a URL, and get the content (see Figure 1 ー 1 ). If she wanted t0 write a blog post, she'd load up her browser, fill out a form, and press submit. When she wanted tO see comments, it was much the same. This has changed. NO longer can a website wait for users t0 navigate t0 the right URL ・ the website must contact the user wherever that user may be. The paradigm has shifted fror れ a website-centric model, where the website was at the center Of the interaction, tO a user-centric model. NOW all interactions start and end at the user (see Fig- ure 1-2 ) , whether she is visiting the website or sending in Short Message Service (SMS) updates. A truly realtime experience exists anywhere the user iS at a given 1 れ omen [. If the user is interacting with the web browser, then that's the place [ 0 contact her. If she's got her instant messenger program open, she'd better be able tO interact with your app from that window.\Vhen she's Offline and your application has an important message for her, send it via SMS. Naturally, you'll need to ask the user's permission before you do some Of these things, but your application needs tO Offer them. 2 ー Chapter l:lntroduction

Building the Realtime User Experience


く b0dy class= yui-skin-sam"> く diV id="container"> a super basic login WindOW - - > く div id="login"> く div class="hd">Enter a username く /diV> く !- く div class="bd"> く ト login window content く input type="text" id="username" / 〉 く input type="button" id="login-button" va1ue="Log ln" / > く /diV> く div class="ft"> く /div> く !- login window titlebar login window fOOter - - > く /html> く /b0dY> く /script> く /diV> く /diV> く script type="text/javascript" lnclude a JavaScript file 千 て om Yahoo! く script type="text/javascript" src="{{ static url(' chat. js' ) }}"> く /script> lnclude our 10Ca1 JS file - src="http://yui.yahooapis.(0m/2.8.Or4/buiId/yui10ader/yui10ader-min.js"> 102 ー Chapter6: Chat our 立 directory. We'll add the 訪 file soon; it's important and does all of the previous chapter. lt's simply using Tornado's static url function to include a file from The way we include the other JavaScript file should look familiar after reading the you'll lose the benefit of the styles provided by the library. it comes time tO render the page. You're free tO change or 01 れ it the class names, but the div and body tags. These classes are used by YUI to style the interface elements when One of the things that sticks out about the HTML shown earlier is the class names for oughly realtime experience. Script intO one download. Fewer downloads means faster load times and a more thor- YUI to determine exactly what needs to be downloaded, and it can combine the Java- clude the JavaScript and CSS dependencies. lncluding the external files like this allows parts 0f the YUI library, we're utilizing YUILoader to automatically calculate and in- that you can use only what you need. Because this application will use a few different interface elements called widgets. YUl allows you tO mix and match components so library. This library includes code for everything from Ajax convenience functions to (Yahoo User lnterface Library (YUI) ( 印 : 〃 怩 lo 〃 げ . ッ わ 00. co 襯 レ 切 JavaScript Script and stylesheets from Yah00!. ln this example, we'll be using some of the great The most important thing tO notice about this page is that we're including some Java- for this application is just a shell of a page with the JavaScript includes that we'll need. based applications; it's not about building a complicated user interface. So our HTML applications behave with the same level Of interactivity and responsiveness as desktop- ThiS chat application iS about demonstrating hOW realtime interfaces can make web

Building the Realtime User Experience


= { } ; / / build the user object var u u . user name user. user name; u . user id user. user id; / / setup the window new YAHOO. widget. Pane1("user-" + user. user id, u. panel { width: " 300PX " , constraintoviewport:true, x: chat. user count * 50 , y: chat. user count * 50 / / set the title of the window u. panel. setHeader("Chatting with " + user. user name); / / add content div, where we' 11 display the chat = document. createE1ement(' div' ) ; var content content. setAttribute(' id' ・ chat-' 十 user. user id); u. panel. appendTOB0dy(content) ; / / the textarea we ・ 11 use to send messages to this user document. createElement('textarea ・ ) ; var textarea textarea. setAttribute(' C01 、 , 36 ) ; textarea. setAttribute(' id ・ 'text- ・ 十 user. user id); u. panel. appendTOB0dy(textarea) ; / / show the online status and hide it after half a second u. panel. setFooter("On1ine.. setTimeout(function() { u. panel. setFooter(' / / keep track 0f a11 0f the connected users. Chat. users[user. user id] / / render the window u. panel. render("container"); つ ; } , 50 の ; There iS quite a bit Of COde in this method, but most 0f it is geared toward creating the HTML elements that are needed ⅲ the actual chat window. The firstthing it does is increment the user count variable. There are ways that we could dynamically figure out hOW many users are connected each time we need tO know, but keeping it calculated in advance 、 vill save S01 れ e computation and lead tO a faster experience browsers with SIOW JavaScript implementations. ミ 、 H わ 角 川 1a れ 記 、 厄 Ⅷ 立 by Nicholas C. zakas (O'ReiIIy). ences. For more information on this topic, I highly recommend the book The speed Of JavaScript is another factor in truly realtime web experi- 114 ー Chapter 6 : Chat object. The login panel is created with an ID that is unique to the user being added. That object contains the user name and user id fields as well as the actual YUI panel the screen, we alSO want tO build aJavaScript Object that represents the user in the COde. ln addition tO creating and showing some HTML elements that represent the user on

Building the Realtime User Experience


Constant width bold Shows commands or other textthat should be typed literally by the user. 朝 月 stant width ゴ t ゴ c Shows text that should be replaced with user-supplied values or by values deter- mined by context. ThiS icon signifies a tip, suggestion, or general note. ThiS icon indicates a warning or caution. Using C0de ExampIes This book is here to help you get your job done. ln general, you may use the code in this bOOk in your programs and documentation. You dO not need tO contact us for permission unless you re reproducing a significant portion Of the COde. For example, writing a program that uses several ChunkS Of COde from this bOOk does not require permission. Selling or distributing a CD-ROM 0f examples from O'Reilly b00ks does require permission. Answering a question by citing this bOOk and quoting example COde does not require permission. lncorporating a significant amount Of example COde from this bOOk intO your product's documentation does require permission. We appreciate, but dO not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "Building ビ Realtime User Experience by Ted Roden. Copyright 2010 0'ReiIIy Media, lnc. , 97 & O ー 596-80615-6. ' ' lfyou feel your use 0f code examples falls outside fair use or the permission given above, feel free tO contact us at 〃 er 川 な 0 〃 S (@ore 〃 い . CO 襯 . [email protected] Books OnIine ・ ・ 》 Safari Books Online is an on-demand digitallibrary that lets you easily Safarl search over 7,500 technology and creative reference bOOks and videos tO 日 00k5 0 れ u00 find the answers you need quickly. x ー Preface

Building the Realtime User Experience


def main(): # setup the specific URL handlers application = webapp. WSGIApp1ication( [ ('/' , MainHandIer) , CoughActionHandIer) , (' /sync/user/? ・ , SyncUserHand1er), ('/get/nearby/germs/? ' GetNearbyGermsHand1er), CoverActionHand1er), ( ' /message/to/germ/host/? ・ MessageToGermHostHand1er) , debug=True) # run the application wsgiref. handlers. CGIHandIer(). run(application) ( 1a55 MessageToGermHostHand1er(webapp. RequestHand1er) : def post(self) : g = Germ ・ get(self. request ・ get(' target_germ_id ' ) ) # a couple Of things happened here: # by sending this message, the current user has instigated # a threat against the enemy use て . # if the enemy responds in two minutes ut = UserThreats(). create(g ・ user, g ・ key(), expires_in minutes=2, challenge_user=users. get current user(), threat type= ' challenge ' ) if ut : mesg = 5e1十 . request ・ get(' msg ・ ) mesg + = "\n\nThis is a direct threat ! protect yourself. Messenger( ). send(from user=users. get current user() , tO user=g. user, body=mesg' response_key=ut. response key) AII the logic in creating a threat like this is already handled by the code we've already written. When we receive this type Of request, we want tO dO tWO separate things. First, we need tO create a new UserThreats Object. By challenging a user, thiS threatens the owner Of the germ, SO we create a threat directed at that user. This threat expires in only tWO minutes because we want the challenged user [ 0 respond quickly. However, this likely happened while the threatened user was not logged into the site. So we must inform that user by sending them a message, complete with the response key that will enable the user to respond from either SMS or XMPP, whichever method is most co ル venient. Figure l() ー 8 shows the flOW Of threats as they function in realtime. Updating threats We're creating and responding tO threats, but because they don't expire, there is no reason for the users t0 respond as they happen. If threats expire without being dealt with, the application needs to penalize the users and tellthem what happened. To do Building the Game ltself ー 259