Download - Real Time Multiplayer in HTML5 - Build New Games

Transcript
  • Design

    Engines

    Graphics

    JavaScript

    Mobile

    Multiplayer

    Platform

    ClassesatBocoupVisualizingDatawithD3.js

    April30May1,Cambridge,MA

    AdsbyBocoup

    BuildNewGamesOpenWebtechniquesforcuttingedgegamedevelopment

    RealTimeMultiplayerinHTML5

    Jul18th,2012|by

    Multiplayerandbrowsers

    Whenyouconsidermakingmultiplayergames,therearemanymethodsavailableforcreatingagamethatfriendscanplayonline.Thereisagoodvarietyofmultiplayergametypestakeforexampleacardgameyouplaysynchronouslywithfriends.Turnsaremade,informationisexchangedin(semi)realtimeandthegameprogressesindiscretesteps.Anotherexample,Chess,canbeasynchronous.Playerstaketheirtime,contemplatingpossibleactionsandplaytheirnextmoveoneweekfromnow.Thesetypesofmultiplayergamesexistinbrowsers,andhaveforalongtime.Thenatureofthebrowseritselfmakesiteasytomakesemirealtimegames,butwewantmorevisceralrealtimeaction.

    CardgamesandChessbothusuallyrequire

    Articles Authors About

    Topics

    SvenBergstrm

  • communicationwithaserverandcommunicationwiththeotherplayersinordertoworkonline.ThisisthefoundationofamultiplayerexperiencetobepossibleandforalongtimethishasexistedviaHTTP,wherePOSTandGEThavealwaysbeenusedtomanagegames.

    Thetroublewiththesemethodsisthedelay,postingamessageandwaitingforaresponseeachtimeisjusttooslow.Itworksforthesemirealtimeandasynchronousgames,butrealtimegamesrequiremessagessentandreceivedsometimesintheregionof33~66timespersecond,somethingthatisnotquitepossiblewithHTTPalone.

    Luckily,inmodernbrowserswecantakeonestephigher,andhavearealtimeconnectionbetweenaserverandclients.Thepurposeofthisdiscussionistopresentoneoverviewofhowmultiplayergamesaremade.Wewilllookatinputprediction,lagcompensation,clientinterpolationandmoreimportantlyhowtodothisinyournormalbrowserusingwebsockets.Thearticlewillpresentaplayabledemowithparameterstoplaywith,showcasingtheconceptsdiscussed.

    Thetechnologiesthatwehavechosenandwhy

    Socket.io

    isapowerfulandflexibleserversideandclientsidecomponentthatenablesrealtimenetworkinginyourbrowser.Notonlydoesitsupportnewertechnologieslikewebsockets,butitalsofallsbacksafelyontoaFlashnetworkinglayer,XHRorJSONlongpollingandevenanHTMLfiletransportlayer.Mostappealingaboutitperhapsisthesimplicityandinherentlyasynchronousnatureitbrings,whichisextremelyusefulwhenwritingserverandclientcode.

    Anotherbenefitofusingsocket.ioisthefactthatitties

    socket.io

  • intoNode.jsseamlessly.WhencoupledwithExpress,onconnection,itcanservetheclientsideincludes,gamefiles,anddata,makingtheintegrationcleanandeasy.Onceyousetitup,theamountofcodebetweenfirstconnectionandcommunicationwithaclientisnothingshortofamazing.Anditwouldworkinallbrowsers,mobileincluded.

    Node.js

    isaneasytouse,flexibleandcrossplatformtool.ItislikeaswissarmyknifeofeventedIO.Ithasamassivefollowingofdedicatedusers,developersandmoduleauthors.Itissupportedonagoodnumberofserverhostingplatformsforwebapplications,andiseasytoinstallonadedicatedserverofyourown,sofindingahostshouldnotbeaproblem.

    AmongmanyofthesegreatmodulesavailableforNode.js,isawebframeworkcalled .Itcoversservingfiles,complexrouting,clientauthenticationandsessions,andmuchmore.Itfitsperfectlyintothestackbetweensocket.ioandourclients,wheresocket.iocanserveitsfilestotheclientsthroughExpressandExpresscanhandlethegamecontentforus.

    Canvas/HTML5

    Thisarticleusesa2Dcanvastodemonstratethemethodswearegoingtocover,whichallowsustodrawsometextandboxesreallyeasily.

    Gettingstartedwitharealtimemultiplayerconnectioninyourbrowser

    Coveringallpossibleoptionsandinstallationsandconfigurationsfortheabovetechnologyisalittleoutofscopeforthisarticle,buteachoftheabovetoolshavetheirowndocumentationandshouldnottakelongtohavesetupandworkingtogether.Forthesakeof

    node.js

    Express

  • brevitywewilldiverightintomakingasimplegameexampleinstead.Theinformationbelowistheminimumrequiredtosetupanemptycanvas,connecttothesocket.ioserverandreceivemessages.

    Startwithasimplewebserver,enterExpress

    ThecodeforasimpleExpressserverisreallyshortandstraightforward.Itservesfilesonaportspecified(4004inthiscase)anditonlyservesfilesfromtherootfolder(likeindex.html),andfromaspecificgamepathwespecify(likegame/).

    Socket.io,addingtherealtimecomponent

    Nowweaddthecodeforthesocket.iopartofthenode.jsserver.ItgoesinthesamefileastheExpresscode,justbelowitasshowninthegist.TheserverwillattachitselftoExpresssothatitmayservetheclientfileswhenrequested.Wedonothandleanysessionsinthisexamplespecifically,butyoucanlearnaboutusingthosefromthissite:

    .

    Index.html,connectingaclienttotheserver

    Theclientsideneedsverylittlecodetobeabletoconnecttotheserver.Aswegofurther,itbecomesmoreintwined,butthisisallthatisrequiredtoconnecttotheserverandsendorreceivedata.

    Gettingintothegameplay

    Whatweneednowisasimpleinteractiveexampleforthistotieinto,togetourfeetwet.Wearegoingtohavetwoblocksrunningaroundinthesamespace.Thereisalotofcodeandlogicthatgoesintocreatingsomethingthatrunssmoothlyovertheinternet,andanygamerelatedcodegettinginthewayisnotas

    http://www.danielbaulig.de/socketioexpress/

  • usefultothisarticle.Instead,wefocusonthemultiplayeranduseasimpleexampletodemonstrate.

    Somenotesondevelopingrealtimegames

    Notalldevelopersmakegames.Therearesomethingsthatarenewtodevelopersthatareenteringtheworldofgamesthatshouldbecoveredbriefly.

    Framerateindependence

    Whenablocktravelsacrossthescreen,itcanbeasimplelineofcode.block.position.x+=1;This1here,whatunitisthatmeasuredin?Actually,thisisonepixelbutitismoving1pixelperframe.Eachtimetheloopruns,wemoveonepixel.Thatisat30framespersecond,itmoves30pixels.At60framespersecond,itmoves60pixels.Thisisreallybadforgames,becausehardwareandperformancecanvaryfromonedeviceorcomputertoanother.Evenbetweendifferentbrowsers,thisproblemcanbeahugedifference.Oneplayerreachesthewall,theotherbarelymovesatall.

    Inordertoensurethattheblockmovesthesamedistanceoverthesameamountoftime,theconceptofdeltatimeisused.Thisvalueisthemillisecondsperframe(mspf),whichismeasuredwhileupdatingyourgame.Itishowlongoneupdatetakes.Bytakingthetimeatthestartofyourloop,andthetimeattheendoftheloop,youcanworkouthowlongtheupdatehastaken.

    At30framespersecond(1/30)thedeltaisabout0.033s.Oneframe,every33.3ms.At60framespersecond(1/60)thedeltaisabout0.016or16.66msperframe.Soletssaythattheballismovingat1pixelperframe.Tosolvetheproblemofframeratedependence,wemultiplyanychangeinpositionbythemspfvalue,balancingoutthetime,makingthedistancealwaysthesame.

  • Ourexamplecalculationbecomesball.position.x+=(1*deltatime);.Withbiggerdelta(slowerframerate)theballmovesmorepixelsreachingthedestinationatthesametimeasatasmallerdelta(higherframerate).Thisgivesusconcreteunitsthatwillactthesameatanyrenderspeed.Thisiscriticalforanimations,movementsandprettymuchanyvaluethatchangesovertime:theyallshouldbescaledtothemspf.

    Planningforchange

    Gamesareoftenadynamicthing:theyrequiretweakingandchangingofmanyvaluestofeelgood.Iterationisabigpartofgettingthisright.Thisiscommonsenseformostprogrammers,butalwaystryanddesignyourcodesothatyouhaveasmanyvaluesandvariablesaspossibletotweak.Thenexposetheminareallyeasytouseplace,soyoucanconstantlyrefinehowthegamefeelsandhowitworkswithoutmuchdiggingandeffort.Tryandbringyouriterationtimedownasmuchaspossible.

    Inthedemoaccompanyingthisarticle,wehaveexposedourvaluesvia sothatyoucanchangeandinteractwiththedemoinrealtime,andfeeltheeffectofthechangesasyoumakethem.

    Multiplayergamesinrealtime

    Gamesareadifficultthingtomake.Gettingthegame

    Dat.GUI

  • playtofeelgood,physicstobesmooth,collisionstobecorrectandcontrolstofeeltightallthesethingstakehardworkalready.Addingamultiplayercomponentmakesthisfarmorecomplex,asthereisnowaserverinvolved.Playersneedtobeinformedofotherplayersactionsbutthereisanetworkdelay.

    Networkingonahighlevel,asimplelobby

    Thewaywewillapproachnetworkingourgameexampleisfairlystraightforward.Ourgameinthisdemocanonlyhavetwoplayersinit,forsimplicity.Inourdemo,aclientconnectstotheserver,thentheservereithergivesthemanexistinggametojoin,orcreatesagameforsomeoneelsetojoin.Thenthegameisaddedtothelistofgamesontheservertoupdate,andtheclientsupdatetheirgameontheirend.Thisisillustratedbelowitworkslikeaverysimplelobbysystem.

    Networkingandthegameloops

    Whenitcomestoarealtimegame,wewanttorunthe

  • gamelogicitselfontheserverANDtheclient.Thisisduetothefactthattheserverneedstobetheauthorityonthestateofthegameatalltimes,buttheclientneedstorunthegamelocallytoo.Eachframeontheserver,inputfromthenetworkwillbeprocessedandappliedtoplayers,andthatchangeissenttotheotherplayersatafixedrate.Ontheclient,inputwillbecollectedandsenttotheserver,andpositionscanbeupdatedwhilewaitingforthemessagestocomebackfromtheserver(clientprediction).

    Theapproachwewillbeimplementingworksasfollows:

    Clientpressestherightkey,clientmovesimmediatelyrightServerreceivestheinputmessageandstoresitforthenextupdateThenextserverupdate,theplayerinputisapplied,movinghimrightontheserverstateAllchangesinstatearesenttoallclientsClientreceivesthemessageimmediatelysettingclientspositions(authoritative)Clientcansmoothlycorrectmistakesinpredictionfromthefirststep

    Thegameserversetup

    Ontheserver,wehavetwoupdatesrunning.Theoneupdateisrunatahighfrequency,whichupdatesthephysicsandstateofthegame.Wewillcallthisthephysicsupdateloop,whichisrunevery15ms(about66updatespersecond).Thesecondupdatewecancalltheserverupdateloop,whichisrunataslowerrate,every45ms(about22updatespersecond).Intheserverupdateloopwesendthestateoftheservertoallclients.Mostofwhatwewillimplementisbasedonthetheorypresentedinthe

    .

    Theserverupdateloopslookslikethis::

    networkingoftheSourceEnginefromValveSoftware

  • Theserverphysicsloop(15ms)

    Dontletthetermphysicsscareyou,inourexampleitisextremelysimplelinearmotion.Wetaketheinputfromtheclients,andwemovethemaccordingtowhattheypushed.Iftheypressleft,youmovethemleft.Whenweaddclientsideprediction,weneedtoalsotelltheclientswhichoftheirinputswehadprocessedlast.Sohowdoesourserverupdatethephysics?

    ProcessinputthatwestoredfromthenetworkWorkoutthedirectiontheyintendedtomovebasedoninputstoredApplythechangesofthisdirectiontotheplayerpositionStorethelastprocessedinputnumberClearanyinputsthatwehavestored

    Theserverupdateloop(45ms)

    Theupdateloopsendsthestateoftheservertoallclients.Thisvariespergameofcourse,andinourexamplethestateconsistsofplayerpositions,theinputsoftheplayerwehavealreadyprocessed(thelastprocessedinputnumber),andthelocalservertime.

    Whatyousendinthestateupdateisuptoyou,andoftenmorethanoneserverupdateloopcanbeemployedtolowertheamountoftrafficused.Asimpleexamplewouldbeaday/nightcycle.Ifthecyclewas

  • changingatamuchlowerratethaneverythingelse,youcansendthestateofthesunevery5secondsinsteadofevery45ms.

    Theclientsetupandupdateloops

    Ontheclientwealsorunmultipleloops,oneforthephysics/gameat15msagain,liketheserver.Thesecondistheregularupdateloop,butinsteadthisonerunsat60fps(preferably),orasfastastheclientcanrunthegame.InHTML5weusuallyrelyonRequestAnimationFrametohandlethisupdate,callingwheneverthebrowserupdatesthewindow.Thisupdateloopisdetailedbelow,andisquitestandard:

    ClearcanvasDrawinfo/statusHandleinput(sendsinputmessagestoserver)Updateposition(usingclientprediction)Movetheotherclientsbasedontheserverposition(interpolation)Drawplayersoncanvas

    Theclientphysicsloop

    Theimportantthingabouttheclientphysicsloophastodowithkeepingtheclientpositionsinsyncwithwhattheserverhasdecidedourpositiontobe.Thismeansthephysicshastomatchtheserverwhenitdecideshowfartomoveus,andthisiswhythephysicsisupdatedatafixedrate.Boththeserverandclientphysicsshouldarriveatthesameconclusion,giventhesameinputs.Ifyouhavepressedrighttwice,theresultsshouldbealmostidenticaltowhattheserverwillcalculateyourpositiontobe.Thisiswhatmakesclientpredictionpossiblewhenattemptingtomaskthedelayinanetworkandtheclients.

    ImportantNetworkingConcepts

    Clientprediction

  • Wehavementionedthisbeforenow,soletstakealookatwhatexactlyitentails.Inanaiveapproachtonetworking,youmighttrythefollowingmodel:

    Clientpressestherightkey,telltheserverMessagearrivesatserversometimeinthefuture(200mslatency)ServersendsbackthenewpositiontotheclientMessagearrivesattheclient(200mslatency)Clientupdatestheirposition400ms+later.

    ThisapproachmightworkwelloverLANconnectionswherethelatencyisreallylow,butwhenconnectingplayerstoaserverviatheInternet,latencycanbeanywherefrom30msto800msrenderingthegameunplayablebecauseofthedelay.Whenyoupushakeytheresponseissobadlydelayedthatitwillnotbeaverygoodgametoplayatall.Buthowdowesolvethis?

    Clientpredictionisthesolution,andsimplymeansactingoninputimmediately,predictingwhattheserverwillcalculateaswell.Weapplyinputwiththeassumptionthatyourresultsandtheserverresults(whenevertheyarrive)willbethesame.Whenaclientpressestherightkeytwice,andendsupatx=2,theserverwillarriveatthesameconclusionandtellyou600mslateryouarestillinthecorrectplace.

    Thisisimportantforimmediatefeedbackontheclientside,andeventhoughupdatesarerunningviaaserver,theclientpositionsshouldmatchup.

    Interpolationofotherclientpositions

    Nowallweneedtoupdateistheotherclientpositions,astheyarrivefromthenetwork.Again,anaiveapproachwouldbetosimplysettheirpositionsassoonasthemessagearrivesfromtheserverbutthisleadstoextremelyjerkyrenderingoftheotherclients.

    Thesolutionistostorethepositionswegetfromtheserverandinterpolatebetweenthem.Thismeansthat

  • wedrawthemafewframesbehindtheserver,butitallowsforverysmoothupdatesofallotherclientpositions.Inourdemo,basedontheSourceEnginearticlelistedabove,wedrawtheotherclients100msbehindtheactualserverpositions.

    Allofthisisimplementedinthedemoandelaboratedonbelowincodeform,butformoreinformationandverygooddiagramsonthetopic,GabrielGambettadidanexcellent ontheconceptspresentedincludingclientprediction,interpolationandthereasonswhytheseworkbestforrealtimegames.Mostimportantforourexampleisthatwestoretheinputsequenceofeachinputtheplayergivesus.Weusethistotrackwheretheserverisinourlistofinputs,andwereprocessinputthattheserverhasnotyetreceived.

    Understandingthedemocode

    Thedemocodepresentedattheendofthearticlefeaturesaworkingsetofthetopicsdiscussed,includingsomedebugcontrolstotweakandseechangesanddifferencesinapproaches.Thedemolookssomethinglikethis:

    Nowthatwehaveseenthetheoryoftheexample,wecanstarttoseehowthecodecomestogether.

    Howthecodeisstructured

    Thecodeinthedemocontainsfourfiles,eachwithdifferentportionsoftheexample.Thefilescontainthefollowinglogic:

    three part series

  • client.jsThelogicforthegameclientsetupinthebrowser.app.jsTheserversideapptorunonnode.Thishandlesallthenode/express/socket.iosetupandcode.game.server.jsThelogicforthegameserver(lobby).game.core.jsThelogicforthegameplayitself,bothserverandclient.

    Coregameplaycode

    Thecodeinsideofgame.core.jsistheimportantpartofourexample.Thecodeissharedbetweenbothserver(runningonnode.js)andtheclient(runninginthebrowser).Thisallowsthecodetousetheexactsamefunctionsandalgorithmstoprocessinput,synchronisemovement,andsharedatastructures.

    Classesofthecoregameplay

    Thegame.core.jsfilehoststhreeclasses,describedindetailbelow.

    Thegame_coreclass

    Thisclassisthedrivingfactorforthewholegamestate.Itrunstheupdatefunctions,ithandlestheoutputsandinputsofthegameandmanagesthegameasitchanges.Thegamecorecanbedescribedasthegameworld.Itcontainstwoplayers,aboundary,anditrunstheworldlogic.Itmakessurethephysicssimulationsarestartedup,itmakessuretheyrunontimeandithandlesthelogicoftheplayersinputs.

    Thegameworldiswheremultiplayerhappens.Wewantthegameworldtoexistinthreeplaces(forthisdemo).Wewanttorunacopyofthegameworldoneachclient,andoneontheserver,pergame.Thisiswhatthelobbydoesingame.server.jsitcreatesaworldforeachsetofplayersthatjoin.

    Allthecodeisnamedaccordingtothepurposeserved.Ifthefunctionnamestartswithclient_,thiscodewill

  • neverbecalledontheserverside.Ifthefunctionbeginswiththetermserver_,similarlythiscodewillnotrunontheclientbuttheserveronly.Allotherfunctionsonthegame_coreclassisdirectlyrelatedtothegamestatethatgetssharedbetweenserverandclient.

    Thegame_playerclass

    Theplayercodeisprobablyalotlighterthanyoumighthaveexpected,buttheplayerclasssimplymaintainsitsownspatialpropertiesandknowshowtodrawitself(ifrequired,likeonthebrowserclient).Ontheserver,ofcourse,thedrawfunctionisjustnevercalled.

    Anexamplefunctionthatissharedbetweentheclientandserver

    Importantfunctionsinthemultiplayercode

    Someofthefunctionsaremoreimportanttomultiplayerthanothers.Letslookattheimportantconceptsoutlinedincode,toseehowtheflowworks.Thecodeexamplesaresometimessimplifiedtodemonstratethekeyconcept.

    Entityinterpolation(otherclients)

    Theinterpolation/smoothingoftheotherclients.Thisishandledinthisfashion:

    Storethenetworkmessagesfromtheserveraboutotherclients,foratleast100msInterpolatebetweenalastknownposition,andanewerpositionintime(100msbehindtheservertime)Drawtheinterpolatedclientsattheinterpolatedposition.

    Thewayweachievethisisasfollows:

  • Clientprediction(localclient)

    Thepredictiontakesplaceintwoplaces,whenreceivingserverauthoritativeresponses,andbeforedrawingweprocessourinputasithappenslocally.Thelogicforthisis:

    HandleinputfromclientStoreinputandthetimeofinputforsmoothinglaterStoretheinputsequenceSendtheinputsandinputsequencetotheserverOnconfirmationfromtheserveroflastknowninputsequence,RemoveinputsthattheserverhasalreadyprocessedReapplyinputsthatstillremaintobeconfirmed

    Hereisthecodesimplifiedtoshowtheinputhandling:

    Conclusionanddemo(codeandlinks)

    Multiplayerisacomplexthing,andhopefullythissimpleexamplehasgivenyouaninsightintoaworldofhavingfriendsplaytogetherinrealtime.

    Viewthedemo

    Getthecode

    Knowyourenemy(furtherdiscussion)

    Keepinmindwhileyouventureintotheworldofrealtimemultiplayeritisbothachallengingandrewardingexperience.Dosomemoreresearchoutsideofthisarticleandfindoutjusthowyourrealtime

    http://underscorediscovery.aws.af.cm/?debug

    https://github.com/FuzzYspo0N/realtimemultiplayerinhtml5

  • gameneedstobestructured.Therearemanygreatresources: hasextensiveexperienceandgenerouslysharesawealthofknowledgeonthetopic.Besuretoreadallofthearticlesonmultiplayerandprogramminggamesthatruninrealtime.Hecoversthebasicsof

    ,andalsojustasimportantishisarticleanddemoon

    .

    AnothersetofgoodarticlesarefromForrestSmith,whoworkedontheSupremeCommanderengineatGasPoweredGames.ThisarticleisaimedatRealtimeStrategyGames(RTS):Thefirstpart,

    andthesecond,.

    Jul18th,2012in.

    Tweet 560 241

    Warning:

    Comments

    Comments Community Login1

    SortbyBest

    Jointhediscussion

    Reply

    McFunkypants 3yearsagoThisisphenomenallyuseful,wellwritten,andprofessional.Thankssomuchfortheamazingexample.I'vedonetonsoflaggyrealtimempusingajaxandphp,whichasyoumightimagineisahugehassleanddoesn'tscaletomorethanahandfulofconcurrentplayers.Keepupthegreatwork!

    18

    skroob 2yearsagoIfyouwanttogetthistoworkwithnewversionofnode:

    Recommend 17

    Share

    GlennFiedler

    WhatEveryGameProgrammerNeedsToKnowAboutNetworking

    NetworkedPhysics

    SynchronousRTSEnginesandaTaleofDesyncsSynchronousRTSEngines2:SyncHarder

    PostedbySvenBergstrmMultiplayer

    116peoplelikethis.Like Share

  • Reply

    ofnode:app.jschange

    line36res.sendfile('index.html',{root:__dirname})

    line52res.sendfile(file,{root:__dirname})

    4

    Reply

    SvenBergstrm 2yearsago

    >skroob

    Thanks,thishasbeenupdatedintherepotoday!

    1

    Reply

    PeterValdez 3yearsagoVeryinterestingreadconsideringthatImyselfusedsocket.io,node.js,andcanvastomakeapetproject(someindividual.com/grid).Notnearlyaspolishedbyanymeans,buthavingsomemultiplayernoFlashappupandrunningwassogratifying.

    Again,greatpost!4

    Reply

    SvenBergstrm 3yearsago

    >PeterValdez

    Itisreallyrewardingindeed:)1

    Skroob 2yearsagoGettingarathernastyerror:

    TypeError:Argumentstopath.joinmustbestrings

    atf(path.js:204:15)

    atObject.filter(native)

    atexports.join(path.js:209:40)

    atexports.send(c:\www\game\node_modules\express\node_modules\connect\lib\m

    iddleware\static.js:129:20)

    atServerResponse.res.sendfile(c:\www\game\node_modules\express\lib\respons

    e.js:186:3)

    atapp.get.file(c:\www\game\app.js:36:13)

    Share

    Share

    Share

    Share

  • Reply

    atapp.get.file(c:\www\game\app.js:36:13)

    atcallbacks(c:\www\game\node_modules\express\lib\router\index.js:272:11)

    atparam(c:\www\game\node_modules\express\lib\router\index.js:246:11)

    atpass(c:\www\game\node_modules\express\lib\router\index.js:253:5)

    atRouter._dispatch(c:\www\game\node_modules\express\lib\router\index.js:28

    0:5)2

    Reply

    SvenBergstrm 2yearsago

    >Skroob

    Thiswasfixedintherepoaswell,itwasjustachangetothewaythepathwashandedin.

    Reply

    PrashantOnkar ayearago

    >SvenBergstrm

    HiSven,Iamgettingthesameerror.Canyoutellmewhatsthefixplease?Iamnewtothissite.

    Reply

    SvenBergstrm

    ayearago

    >PrashantOnkar

    Youmightbelookingforthischangespecifically?https://github.com/underscored...

    Ifyouhavethecodefromtherepo,itwouldautomaticallybeinthelatestcode,unlesssomethinghaschangedsincebutnobodyhasreportedanyissuessofar.

    Reply

    eldad87 2yearsago>SkroobI'mgettingthesamething.

    SvenBergstrm 2yearsago

    >eldad87

    seecommentabove:)

    Share

    Share

    Share

    Share

    Share

  • Reply seecommentabove:)

    Reply

    MiguelRipoll 2yearsagoThisarticlehelpedmealot,thanks!

    1

    Reply

    Genkikami 2yearsagoOkaysoIamtryingtojustuseyourtutorialforsettingupthebasicwebserver.SoIcopiedtheexpressandsocket.iocodenearthetopintothesamefile(app.js)andtheonlythingIchangedistheline:

    res.sendfile(__dirname+'/index.html')

    ThenwhenIcompiledtheprogramonmycommandlinewith"nodeapp.js".ItcompilesbutassoonItrytoconnecttotheserverthroughmy"localhost:4004"Igottheerror"Error:ENOENT,stat'....\node_modules\socket.io\socket.io.js".Ichangedthepathintheindex.htmlfilethatIsendfromtheservertobe:

    Butthisresultsinthiserrorinmywebbrowserconsole:

    SobasicallyistheresomethingbigthatIammissing?Suggestionswelcome:).UncaughtReferenceError:requireisnotdefinedsocket.io.js:12UncaughtReferenceError:ioisnotdefinedlocalhost/:26

    1

    Genkikami 2yearsago>GenkikamiOkaysoigotitworkingineededtochangethestartercodefortheserverinorderforittowork:varhttp=require('http'),server=http.createServer(app)

    Bothoftheseneededtobeaddedandthenchangetheline:

    app.listen(gameport)

    Share

    Share

    Share

  • Reply

    to

    server.listen(gameport)

    andchangetheline:

    varsio=io.listen(app)

    to

    varsio=io.listen(server)

    Theneverythingcompiledfineandranwithnoerrorsinthebrowser.

    1

    Reply

    SvenBergstrm 2yearsago

    >Genkikami

    Thanksbtw,forcommenting.Thiswasupdatedintherepotoday,buthadbeeninthepullrequestsforawhileIhadjustbeenoccupiedelsewhere.

    Reply

    AsadMemon 2yearsagoIamworkingonaddingsupporttomorethantwoplayerstothisproject.Feelfreetocheckit.https://github.com/asadlionpk/...

    1

    Reply

    Colton 10monthsago>AsadMemonI'mgettinganerrorfromyourproject:TypeError:Argumentstopath.joinmustbestringsatf(path.js..)

    ...AndIamnotseeingafix.Anyideas?

    Reply

    Divyanshu 2yearsagoCanSomeonepleasetellme,whereandhowtolearnnode.jsorserver.io,asisearchedalotthereisnotevenasinglegoodtutorialtostartwiththebeginning,shouldihavetobuyabook?Ifsopleasesuggestagoodbook!Reallyneedtocheckthesefeatures,thanksinadvance!!:)

    1

    Share

    Share

    Share

    Share

    Share

  • Reply

    Abhi 2yearsagothisisbrilliant,thankyou

    1

    Reply

    DushanNedelkovich 2yearsagodemolinkisnotworking:(

    1

    Reply

    incompl 2yearsago

    >DushanNedelkovich

    Ifixedthelink,thanksforpointingthisout!

    Reply

    Frowz 2yearsago>incomplVeryinteresting,ilearningnode.jsorserver.io,keepupthegreatwork!

    Reply

    SvenBergstrm 2yearsago

    >DushanNedelkovich

    http://underscorediscovery.aws...

    Reply

    Sandy 3yearsagolearnalot,Thanks

    1

    Reply

    GlennFiedler 3yearsagoAverywellwrittenarticle.Goodjob!

    1

    FlorianBsch 3yearsagoNoteacoupleofthings:1)You*have*toconfiguresocket.iotousewebsocketsonly,orit'lltrytofallbacktoXHRsorJSONP,whichare(asyoudescribed)woefullyinadequateforanythingapproachingrealtimecommunication.2)WebSocketsarebasedonTPC/IP,whichwhilegoodandreliable,isnotaveryfastprotocolanditusuallyincursuptomultiplesecondsoflatencywhengoinglongerdistances(syn,ack,ack,syn,etc.).3)UDPwouldbemoresuitableforgames,howeverbrowsersdonotsupportthatyet.4)However,WebRTCisaddinganunreliabledgramchanneltoit'sprotocol,whichis,effectively,UDP.Thisisexpectedtolandinlate2012

    Share

    Share

    Share

    Share

    Share

    Share

    Share

  • Reply 2012

    1

    Reply

    SvenBergstrm 3yearsago

    >FlorianBsch

    Yep!Iamconfidentthatsocket.iowillmakeadditionalsupportforthattoo!

    Websocketsaredefinitelythebestoption,thoughforlessinstantaneousgamesyoucouldeasilyfallbacksafely.

    1

    Reply

    Angelblade 3yearsagoAmazing,wonderful,thankyousomuch

    1

    Reply

    realUser404 3monthsagoToobadmanypartsofthecodearedeprecatednow

    Reply

    Lucidbrot 3monthsagores.sendfileisdeprecatedyoushouldnowuseres.sendFileinstead

    Reply

    thegreat1200 3monthsagoHowwouldIaddusernamesandchat(withcommands)?Also,canIhavemorethan2playersconnectedtothesameroom/server?Icanonlyget2toconnect.

    Reply

    HaseebAhmad 8monthsagoI'mplanningtomakeBrowserbasedmultiplayergameasafinalprojectinBSComputerScience.Thisarticlewasveryhelpful.Formyproject,I'mthinkingjavascriptforclientsideandjavaasserverside.Ifyoucouldsuggestsomearticleoranythingformyproject,thatwouldbeverynice.

    Reply

    MnhM ayearagoThisarticleissouseful,thankyouverymuch

    RickS ayearagonode.jsisverypoorlydocumentedfornewusers.

    Share

    Share

    Share

    Share

    Share

    Share

    Share

    Share

  • Reply

    node.jsisverypoorlydocumentedfornewusers.Onlinetutorialsareevenworsewhenexplaininghowtouseit'sI/OandSockets

    Edit:donotevenbotherwiththisThereareno(good)webhoststhathassocket.io,node.jsorexpress.jssupport.IfyouhavetheenergyandtimetofightAmazonhostingbemyguest.I'llsticktoJava.

    Reply

    swifton 4monthsago>RickSWhataboutheroku?Isn'tthatagoodwebhost?

    Reply

    Mane ayearago>RickSYes,Iagree,node.jsdocumentationisdirectlyjustapidocwhatitincludes,sogooglingaroundhowtouseitisfasterthanactuallyreadingit.Andasforthewebhosts..Whatyouaretalkingabout?Whataboutheroku?nodejitsu(firstwithpropersocket.iosupport?)andspeakingofhostsandthelaginthisdemoIassumethatitisrunningonsomefreeinstancewhichhashighlatency.BUT,Ifyouareabouttomakeagame,settingupproperserverwithgoodCPUandlowlatencymightbeneededanyway..Ihaven'tdoneanycalculationsbutIfearthatthose"dynolike"herokuetc.solutionsmightnotbeaproperwaytogo..soyoueventuallyhavetofighttosetupgoodserver)

    Reply

    RickS ayearago>ManeOneword:GitHub...Ican'tNOPEloudenoughwheneverasitedeclaresGetHubmandatory.Ilivein2014,not1995.

    1

    Reply

    Mane ayearago

    >RickS

    WhattheheckisGetHub?1

    Share

    Share

    Share

    Share

    Share

    relatedarticles

  • morestuff

    EditedandoperatedbyBocoup.

    EditedandoperatedbyBocoup

    TeamSnake:APostMortem byDariusKazemiOptimizingWebSocketsBandwidth byEricLiWebSockets:AGuide byJackLawson

    Creatinga3DgamewithThree.jsandWebGL byNikhilSureshSimulatingNaturalSystemsinaWebBrowser byVinceAllenMakingGamesFun byBurakKanberVectorFieldObstacleAvoidance byAlexanderSutherlandAnintroductiontotheCraftygameengine byDarrenTorpey

    Home