Recallthat HTTP is request/response protocol · •Recallthat HTTP is request/response protocol...

Post on 22-Aug-2020

5 views 0 download

Transcript of Recallthat HTTP is request/response protocol · •Recallthat HTTP is request/response protocol...

• Recall thatHTTPisrequest/responseprotocol• AJAX allowsyoutodoHTTPrequest/responsewithinapage,butitisstillrequest/response

• Aclientalwayshastoinitiatecommunication.– I.e.Maketherequest

• Whatifyouwanttheservertobeableto"push"informationdowntotheclient,forexample:– Newemail– Newnews– Updatestoasharedchat/drawingcanvas– Gameevents

©JoeMertz– MobiletoCloud:BuildingDistributedApplications

• Workarounds havebeendevised• E.g.Polling

– Client continuouslypollstheserver• E.g.LongPolling

– Clientsendsarequest,whichtheserverdoesnotrespondtountilithassomethingtosend

– Ifsomethingcomesalongtosend,itcompletestheresponseandtheclientwillimmediatelysendanewrequesttoholdontoforlater

– Iftherequesttimesout,theclientsendsanewresponse.– Analogy(fromthedaysofpostalmail)…

• Cheapfriendcan'taffordstamps.• Sendfriendstamp,heusesittosendyoualetter• Whenyoureceivemessage,immediatelysendhimanotherstampforthenexttimehewantstosendaletter.

©JoeMertz– MobiletoCloud:BuildingDistributedApplications

• Providesfortrue two-way ongoing communicationbetweenaclientandserver.

• Eachsidecan"send"messages.• Eachsidehaslistener"onmessage"• WebSockets arenotrestrictedbytheSameOriginPolicy– It isuptotheservertochecktheOriginheaderanddecidewhetheritshouldreplyornot.

• Note:– Someold browsersdon't implementWebSockets

©JoeMertz– MobiletoCloud:BuildingDistributedApplications

// Create a new WebSocketvar wSocket = new WebSocket("ws://www.example.com/socketserver")

// When the WebSocket is connected and readywSocket.onopen = function (event) {

// Send a message to the serverwSocket.send("Initial message to the server.");

};

// Handler for when a message arrives from the serverwSocket.onmessage = function (event) {

console.log(event.data);};

©JoeMertz– MobiletoCloud:BuildingDistributedApplications

©JoeMertz– MobiletoCloud:BuildingDistributedApplications

• RequireaWebSockets module– ws isverypopular– https://www.npmjs.com/package/ws

• CreateanewWebSockets Server• Definehandlersfor– onconnection– onmessage

• Andsendmessagestotheclient

• Library forfull-duplexcommunicationbetweenclientsandservers

• Builtonengine.io,socket.io providesanabstractionabovewhatevertransportmethodsareavailable inthebrowser:–WebSockets– LongPolling

©JoeMertz– MobiletoCloud:BuildingDistributedApplications

• Alsoprovidesasimpleabstractionfor event-basedprogrammingacrosstheserverandmultipleclients

• Clientscan– emiteventsbacktotheserver– listenforeventsfromtheserver

• Servercan– listen foreventsfromclients– emiteventsbacktotheclient– emiteventstootherclients– broadcastemiteventstoallclients

©JoeMertz– MobiletoCloud:BuildingDistributedApplications

• Ateachtable,createagame• Aneventissimplyaword

– Itcanoptionallybeaccompaniedwithashortphrase• OnepersonistheServerwhocan:

– listen foreventsfromclients– emitaneventtooneclient(pointtooneandsay…)– broadcast emiteventstoall clients(pointwithbothhandsandsay…)

• TherestatthetableareClientswhocan– emiteventstotheserver– listenforeventsfromtheserver

• ClientsortheServercangenerateeventsatanytime(dependingonyourgame-play)

• Clientscannotemiteventspeer-to-peer(Servermustrelay)©JoeMertz– MobiletoCloud:BuildingDistributedApplications

• on(event,function(parameter-object){…}• emit(event,parameter-object)• events– connection– disconnect– developer-definedevents

©JoeMertz– MobiletoCloud:BuildingDistributedApplications

• socket.emit(…)– emitsbacktotheclient

• socket.broadcast.emit(…)– emitstoallconnectedclientsexceptthe socketthatstartsit

©JoeMertz– MobiletoCloud:BuildingDistributedApplications

• Demo• Codewalkthrough

©JoeMertz– MobiletoCloud:BuildingDistributedApplications

1. AddawelcomemessagetocountPlayers–Whenanewplayerconnects– Serveremitsa"welcome"eventtoit

• Dataoftheeventis{message:"Welcomeplayern"}– Where"n"istheordinalnumberoftheplayerwhohasjoined

2. Createasimpleappinwhichuserscollaborate/compete/communicate.– Actionsbyeachuserisbroadcasttoallusers– Periodically(e.g.everyonesecond)serverbroadcasts

somethingtoallusers

©JoeMertz– MobiletoCloud:BuildingDistributedApplications