Real Time Multiplayer in HTML5 - Build New Games
Real Time Multiplayer in HTML5 - Build New Games
Authors
About
BuildNewGames
OpenWebtechniquesforcuttingedgegame
development
Topics
Design
Engines
RealTime
Multiplayerin
HTML5
Graphics
JavaScript
Jul18th,2012|bySvenBergstrm
Mobile
Multiplayerandbrowsers
Multiplayer
Whenyouconsidermakingmultiplayergames,there
aremanymethodsavailableforcreatingagamethat
friendscanplayonline.Thereisagoodvarietyof
multiplayergametypestakeforexampleacardgame
youplaysynchronouslywithfriends.Turnsaremade,
informationisexchangedin(semi)realtimeandthe
gameprogressesindiscretesteps.Anotherexample,
ClassesatBocoup
Chess,canbeasynchronous.Playerstaketheirtime,
VisualizingDatawithD3.js
contemplatingpossibleactionsandplaytheirnext
April30May1,Cambridge,MA moveoneweekfromnow.Thesetypesofmultiplayer
gamesexistinbrowsers,andhaveforalongtime.The
Adsby
natureofthebrowseritselfmakesiteasytomakesemi
Bocoup
realtimegames,butwewantmorevisceralrealtime
action.
Platform
CardgamesandChessbothusuallyrequire
communicationwithaserverandcommunicationwith
theotherplayersinordertoworkonline.Thisisthe
foundationofamultiplayerexperiencetobepossible
andforalongtimethishasexistedviaHTTP,where
POSTandGEThavealwaysbeenusedtomanage
games.
Thetroublewiththesemethodsisthedelay,postinga
messageandwaitingforaresponseeachtimeisjust
tooslow.Itworksforthesemirealtimeand
asynchronousgames,butrealtimegamesrequire
messagessentandreceivedsometimesintheregionof
33~66timespersecond,somethingthatisnotquite
possiblewithHTTPalone.
Luckily,inmodernbrowserswecantakeonestep
higher,andhavearealtimeconnectionbetweena
serverandclients.Thepurposeofthisdiscussionisto
presentoneoverviewofhowmultiplayergamesare
made.Wewilllookatinputprediction,lag
compensation,clientinterpolationandmore
importantlyhowtodothisinyournormalbrowser
usingwebsockets.Thearticlewillpresentaplayable
demowithparameterstoplaywith,showcasingthe
conceptsdiscussed.
Thetechnologiesthatwehave
chosenandwhy
Socket.io
socket.ioisapowerfulandflexibleserversideand
clientsidecomponentthatenablesrealtime
networkinginyourbrowser.Notonlydoesitsupport
newertechnologieslikewebsockets,butitalsofalls
backsafelyontoaFlashnetworkinglayer,XHRor
JSONlongpollingandevenanHTMLfiletransport
layer.Mostappealingaboutitperhapsisthesimplicity
andinherentlyasynchronousnatureitbrings,whichis
extremelyusefulwhenwritingserverandclientcode.
Anotherbenefitofusingsocket.ioisthefactthatitties
intoNode.jsseamlessly.WhencoupledwithExpress,
onconnection,itcanservetheclientsideincludes,
gamefiles,anddata,makingtheintegrationcleanand
easy.Onceyousetitup,theamountofcodebetween
firstconnectionandcommunicationwithaclientis
nothingshortofamazing.Anditwouldworkinall
browsers,mobileincluded.
Node.js
node.jsisaneasytouse,flexibleandcrossplatform
tool.ItislikeaswissarmyknifeofeventedIO.Ithasa
massivefollowingofdedicatedusers,developersand
moduleauthors.Itissupportedonagoodnumberof
serverhostingplatformsforwebapplications,andis
easytoinstallonadedicatedserverofyourown,so
findingahostshouldnotbeaproblem.
Amongmanyofthesegreatmodulesavailablefor
Node.js,isawebframeworkcalledExpress.Itcovers
servingfiles,complexrouting,clientauthentication
andsessions,andmuchmore.Itfitsperfectlyintothe
stackbetweensocket.ioandourclients,where
socket.iocanserveitsfilestotheclientsthrough
ExpressandExpresscanhandlethegamecontentfor
us.
Canvas/HTML5
Thisarticleusesa2Dcanvastodemonstratethe
methodswearegoingtocover,whichallowsusto
drawsometextandboxesreallyeasily.
Gettingstartedwitharealtime
multiplayerconnectioninyour
browser
Coveringallpossibleoptionsandinstallationsand
configurationsfortheabovetechnologyisalittleoutof
scopeforthisarticle,buteachoftheabovetoolshave
theirowndocumentationandshouldnottakelongto
havesetupandworkingtogether.Forthesakeof
brevitywewilldiverightintomakingasimplegame
exampleinstead.Theinformationbelowisthe
minimumrequiredtosetupanemptycanvas,connect
tothesocket.ioserverandreceivemessages.
Startwithasimplewebserver,enter
Express
ThecodeforasimpleExpressserverisreallyshortand
straightforward.Itservesfilesonaportspecified
(4004inthiscase)anditonlyservesfilesfromthe
rootfolder(likeindex.html),andfromaspecificgame
pathwespecify(likegame/).
Socket.io,addingtherealtime
component
Nowweaddthecodeforthesocket.iopartofthe
node.jsserver.ItgoesinthesamefileastheExpress
code,justbelowitasshowninthegist.Theserverwill
attachitselftoExpresssothatitmayservetheclient
fileswhenrequested.Wedonothandleanysessionsin
thisexamplespecifically,butyoucanlearnaboutusing
thosefromthissite:
http://www.danielbaulig.de/socketioexpress/.
Index.html,connectingaclienttothe
server
Theclientsideneedsverylittlecodetobeableto
connecttotheserver.Aswegofurther,itbecomes
moreintwined,butthisisallthatisrequiredto
connecttotheserverandsendorreceivedata.
Gettingintothegameplay
Whatweneednowisasimpleinteractiveexamplefor
thistotieinto,togetourfeetwet.Wearegoingtohave
twoblocksrunningaroundinthesamespace.Thereis
alotofcodeandlogicthatgoesintocreating
somethingthatrunssmoothlyovertheinternet,and
anygamerelatedcodegettinginthewayisnotas
usefultothisarticle.Instead,wefocusonthe
multiplayeranduseasimpleexampletodemonstrate.
Somenotesondevelopingrealtime
games
Notalldevelopersmakegames.Therearesomethings
thatarenewtodevelopersthatareenteringtheworld
ofgamesthatshouldbecoveredbriefly.
Framerateindependence
Whenablocktravelsacrossthescreen,itcanbea
simplelineofcode.block.position.x+=1;This1here,
whatunitisthatmeasuredin?Actually,thisisone
pixelbutitismoving1pixelperframe.Eachtimethe
loopruns,wemoveonepixel.Thatisat30frames
persecond,itmoves30pixels.At60framesper
second,itmoves60pixels.Thisisreallybadfor
games,becausehardwareandperformancecanvary
fromonedeviceorcomputertoanother.Evenbetween
differentbrowsers,thisproblemcanbeahuge
difference.Oneplayerreachesthewall,theother
barelymovesatall.
Inordertoensurethattheblockmovesthesame
distanceoverthesameamountoftime,theconceptof
deltatimeisused.Thisvalueisthemillisecondsper
frame(mspf),whichismeasuredwhileupdatingyour
game.Itishowlongoneupdatetakes.Bytakingthe
timeatthestartofyourloop,andthetimeattheend
oftheloop,youcanworkouthowlongtheupdatehas
taken.
At30framespersecond(1/30)thedeltaisabout
0.033s.Oneframe,every33.3ms.At60framesper
second(1/60)thedeltaisabout0.016or16.66msper
frame.Soletssaythattheballismovingat1pixelper
frame.Tosolvetheproblemofframeratedependence,
wemultiplyanychangeinpositionbythemspfvalue,
balancingoutthetime,makingthedistancealwaysthe
same.
Ourexamplecalculationbecomesball.position.x+=
(1*deltatime);.Withbiggerdelta(slowerframerate)
theballmovesmorepixelsreachingthedestination
atthesametimeasatasmallerdelta(higherframe
rate).Thisgivesusconcreteunitsthatwillactthe
sameatanyrenderspeed.Thisiscriticalfor
animations,movementsandprettymuchanyvalue
thatchangesovertime:theyallshouldbescaledtothe
mspf.
Planningforchange
Gamesareoftenadynamicthing:theyrequire
tweakingandchangingofmanyvaluestofeelgood.
Iterationisabigpartofgettingthisright.Thisis
commonsenseformostprogrammers,butalwaystry
anddesignyourcodesothatyouhaveasmanyvalues
andvariablesaspossibletotweak.Thenexposethem
inareallyeasytouseplace,soyoucanconstantly
refinehowthegamefeelsandhowitworkswithout
muchdiggingandeffort.Tryandbringyouriteration
timedownasmuchaspossible.
Inthedemoaccompanyingthisarticle,wehave
exposedourvaluesviaDat.GUIsothatyoucanchange
andinteractwiththedemoinrealtime,andfeelthe
effectofthechangesasyoumakethem.
Multiplayergamesinrealtime
Gamesareadifficultthingtomake.Gettingthegame
playtofeelgood,physicstobesmooth,collisionstobe
correctandcontrolstofeeltightallthesethingstake
hardworkalready.Addingamultiplayercomponent
makesthisfarmorecomplex,asthereisnowaserver
involved.Playersneedtobeinformedofotherplayers
actionsbutthereisanetworkdelay.
Networkingonahighlevel,asimple
lobby
Thewaywewillapproachnetworkingourgame
exampleisfairlystraightforward.Ourgameinthis
democanonlyhavetwoplayersinit,forsimplicity.In
ourdemo,aclientconnectstotheserver,thenthe
servereithergivesthemanexistinggametojoin,or
createsagameforsomeoneelsetojoin.Thenthegame
isaddedtothelistofgamesontheservertoupdate,
andtheclientsupdatetheirgameontheirend.Thisis
illustratedbelowitworkslikeaverysimplelobby
system.
Networkingandthegame
loops
Whenitcomestoarealtimegame,wewanttorunthe
gamelogicitselfontheserverANDtheclient.Thisis
duetothefactthattheserverneedstobetheauthority
onthestateofthegameatalltimes,buttheclient
needstorunthegamelocallytoo.Eachframeonthe
server,inputfromthenetworkwillbeprocessedand
appliedtoplayers,andthatchangeissenttotheother
playersatafixedrate.Ontheclient,inputwillbe
collectedandsenttotheserver,andpositionscanbe
updatedwhilewaitingforthemessagestocomeback
fromtheserver(clientprediction).
Theapproachwewillbeimplementingworksas
follows:
Clientpressestherightkey,clientmoves
immediatelyright
Serverreceivestheinputmessageandstoresitfor
thenextupdate
Thenextserverupdate,theplayerinputisapplied,
movinghimrightontheserverstate
Allchangesinstatearesenttoallclients
Clientreceivesthemessageimmediatelysetting
clientspositions(authoritative)
Clientcansmoothlycorrectmistakesinprediction
fromthefirststep
Thegameserversetup
Ontheserver,wehavetwoupdatesrunning.Theone
updateisrunatahighfrequency,whichupdatesthe
physicsandstateofthegame.Wewillcallthisthe
physicsupdateloop,whichisrunevery15ms(about66
updatespersecond).Thesecondupdatewecancall
theserverupdateloop,whichisrunataslowerrate,
every45ms(about22updatespersecond).Inthe
serverupdateloopwesendthestateoftheservertoall
clients.Mostofwhatwewillimplementisbasedonthe
theorypresentedinthenetworkingoftheSource
EnginefromValveSoftware.
Theserverupdateloopslookslikethis::
Theserverphysicsloop(15ms)
Dontletthetermphysicsscareyou,inourexampleit
isextremelysimplelinearmotion.Wetaketheinput
fromtheclients,andwemovethemaccordingtowhat
theypushed.Iftheypressleft,youmovethemleft.
Whenweaddclientsideprediction,weneedtoalso
telltheclientswhichoftheirinputswehadprocessed
last.Sohowdoesourserverupdatethephysics?
Processinputthatwestoredfromthenetwork
Workoutthedirectiontheyintendedtomove
basedoninputstored
Applythechangesofthisdirectiontotheplayer
position
Storethelastprocessedinputnumber
Clearanyinputsthatwehavestored
Theserverupdateloop(45ms)
Theupdateloopsendsthestateoftheservertoall
clients.Thisvariespergameofcourse,andinour
examplethestateconsistsofplayerpositions,the
inputsoftheplayerwehavealreadyprocessed(thelast
processedinputnumber),andthelocalservertime.
Whatyousendinthestateupdateisuptoyou,and
oftenmorethanoneserverupdateloopcanbe
employedtolowertheamountoftrafficused.Asimple
examplewouldbeaday/nightcycle.Ifthecyclewas
changingatamuchlowerratethaneverythingelse,
youcansendthestateofthesunevery5seconds
insteadofevery45ms.
Theclientsetupandupdateloops
Ontheclientwealsorunmultipleloops,oneforthe
physics/gameat15msagain,liketheserver.The
secondistheregularupdateloop,butinsteadthisone
runsat60fps(preferably),orasfastastheclientcan
runthegame.InHTML5weusuallyrelyon
RequestAnimationFrametohandlethisupdate,calling
wheneverthebrowserupdatesthewindow.This
updateloopisdetailedbelow,andisquitestandard:
Clearcanvas
Drawinfo/status
Handleinput(sendsinputmessagestoserver)
Updateposition(usingclientprediction)
Movetheotherclientsbasedontheserverposition
(interpolation)
Drawplayersoncanvas
Theclientphysicsloop
Theimportantthingabouttheclientphysicsloophas
todowithkeepingtheclientpositionsinsyncwith
whattheserverhasdecidedourpositiontobe.This
meansthephysicshastomatchtheserverwhenit
decideshowfartomoveus,andthisiswhythephysics
isupdatedatafixedrate.Boththeserverandclient
physicsshouldarriveatthesameconclusion,giventhe
sameinputs.Ifyouhavepressedrighttwice,the
resultsshouldbealmostidenticaltowhattheserver
willcalculateyourpositiontobe.Thisiswhatmakes
clientpredictionpossiblewhenattemptingtomaskthe
delayinanetworkandtheclients.
ImportantNetworking
Concepts
Clientprediction
Wehavementionedthisbeforenow,soletstakealook
atwhatexactlyitentails.Inanaiveapproachto
networking,youmighttrythefollowingmodel:
Clientpressestherightkey,telltheserver
Messagearrivesatserversometimeinthefuture(
200mslatency)
Serversendsbackthenewpositiontotheclient
Messagearrivesattheclient(200mslatency)
Clientupdatestheirposition400ms+later.
ThisapproachmightworkwelloverLANconnections
wherethelatencyisreallylow,butwhenconnecting
playerstoaserverviatheInternet,latencycanbe
anywherefrom30msto800msrenderingthegame
unplayablebecauseofthedelay.Whenyoupushakey
theresponseissobadlydelayedthatitwillnotbea
verygoodgametoplayatall.Buthowdowesolve
this?
Clientpredictionisthesolution,andsimplymeans
actingoninputimmediately,predictingwhatthe
serverwillcalculateaswell.Weapplyinputwiththe
assumptionthatyourresultsandtheserverresults
(whenevertheyarrive)willbethesame.Whenaclient
pressestherightkeytwice,andendsupatx=2,the
serverwillarriveatthesameconclusionandtellyou
600mslateryouarestillinthecorrectplace.
Thisisimportantforimmediatefeedbackontheclient
side,andeventhoughupdatesarerunningviaaserver,
theclientpositionsshouldmatchup.
Interpolationofotherclientpositions
Nowallweneedtoupdateistheotherclientpositions,
astheyarrivefromthenetwork.Again,anaive
approachwouldbetosimplysettheirpositionsas
soonasthemessagearrivesfromtheserverbutthis
leadstoextremelyjerkyrenderingoftheotherclients.
Thesolutionistostorethepositionswegetfromthe
serverandinterpolatebetweenthem.Thismeansthat
wedrawthemafewframesbehindtheserver,butit
allowsforverysmoothupdatesofallotherclient
positions.Inourdemo,basedontheSourceEngine
articlelistedabove,wedrawtheotherclients100ms
behindtheactualserverpositions.
Allofthisisimplementedinthedemoandelaborated
onbelowincodeform,butformoreinformationand
verygooddiagramsonthetopic,GabrielGambettadid
anexcellentthreepartseriesontheconcepts
presentedincludingclientprediction,interpolation
andthereasonswhytheseworkbestforrealtime
games.Mostimportantforourexampleisthatwe
storetheinputsequenceofeachinputtheplayergives
us.Weusethistotrackwheretheserverisinourlist
ofinputs,andwereprocessinputthattheserverhas
notyetreceived.
Understandingthedemocode
Thedemocodepresentedattheendofthearticle
featuresaworkingsetofthetopicsdiscussed,
includingsomedebugcontrolstotweakandsee
changesanddifferencesinapproaches.Thedemo
lookssomethinglikethis:
Nowthatwehaveseenthetheoryoftheexample,we
canstarttoseehowthecodecomestogether.
Howthecodeisstructured
Thecodeinthedemocontainsfourfiles,eachwith
differentportionsoftheexample.Thefilescontainthe
followinglogic:
client.jsThelogicforthegameclientsetupinthe
browser.
app.jsTheserversideapptorunonnode.This
handlesallthenode/express/socket.iosetupand
code.
game.server.jsThelogicforthegameserver
(lobby).
game.core.jsThelogicforthegameplayitself,both
serverandclient.
Coregameplaycode
Thecodeinsideofgame.core.jsistheimportantpartof
ourexample.Thecodeissharedbetweenbothserver
(runningonnode.js)andtheclient(runninginthe
browser).Thisallowsthecodetousetheexactsame
functionsandalgorithmstoprocessinput,synchronise
movement,andsharedatastructures.
Classesofthecoregameplay
Thegame.core.jsfilehoststhreeclasses,describedin
detailbelow.
Thegame_coreclass
Thisclassisthedrivingfactorforthewholegame
state.Itrunstheupdatefunctions,ithandlesthe
outputsandinputsofthegameandmanagesthegame
asitchanges.Thegamecorecanbedescribedasthe
gameworld.Itcontainstwoplayers,aboundary,and
itrunstheworldlogic.Itmakessurethephysics
simulationsarestartedup,itmakessuretheyrunon
timeandithandlesthelogicoftheplayersinputs.
Thegameworldiswheremultiplayerhappens.We
wantthegameworldtoexistinthreeplaces(forthis
demo).Wewanttorunacopyofthegameworldon
eachclient,andoneontheserver,pergame.Thisis
whatthelobbydoesingame.server.jsitcreatesa
worldforeachsetofplayersthatjoin.
Allthecodeisnamedaccordingtothepurposeserved.
Ifthefunctionnamestartswithclient_,thiscodewill
neverbecalledontheserverside.Ifthefunction
beginswiththetermserver_,similarlythiscodewill
notrunontheclientbuttheserveronly.Allother
functionsonthegame_coreclassisdirectlyrelatedto
thegamestatethatgetssharedbetweenserverand
client.
Thegame_playerclass
Theplayercodeisprobablyalotlighterthanyou
mighthaveexpected,buttheplayerclasssimply
maintainsitsownspatialpropertiesandknowshowto
drawitself(ifrequired,likeonthebrowserclient).On
theserver,ofcourse,thedrawfunctionisjustnever
called.
Anexamplefunctionthatissharedbetween
theclientandserver
Importantfunctionsinthe
multiplayercode
Someofthefunctionsaremoreimportantto
multiplayerthanothers.Letslookattheimportant
conceptsoutlinedincode,toseehowtheflowworks.
Thecodeexamplesaresometimessimplifiedto
demonstratethekeyconcept.
Entityinterpolation(otherclients)
Theinterpolation/smoothingoftheotherclients.This
ishandledinthisfashion:
Storethenetworkmessagesfromtheserverabout
otherclients,foratleast100ms
Interpolatebetweenalastknownposition,anda
newerpositionintime(100msbehindtheserver
time)
Drawtheinterpolatedclientsattheinterpolated
position.
Thewayweachievethisisasfollows:
Clientprediction(localclient)
Thepredictiontakesplaceintwoplaces,when
receivingserverauthoritativeresponses,andbefore
drawingweprocessourinputasithappenslocally.
Thelogicforthisis:
Handleinputfromclient
Storeinputandthetimeofinputforsmoothing
later
Storetheinputsequence
Sendtheinputsandinputsequencetotheserver
Onconfirmationfromtheserveroflastknown
inputsequence,
Removeinputsthattheserverhasalready
processed
Reapplyinputsthatstillremaintobeconfirmed
Hereisthecodesimplifiedtoshowtheinputhandling:
Conclusionanddemo(code
andlinks)
Multiplayerisacomplexthing,andhopefullythis
simpleexamplehasgivenyouaninsightintoaworld
ofhavingfriendsplaytogetherinrealtime.
Viewthedemo
http://underscorediscovery.aws.af.cm/?debug
Getthecode
https://github.com/FuzzYspo0N/realtime
multiplayerinhtml5
Knowyourenemy(furtherdiscussion)
Keepinmindwhileyouventureintotheworldofreal
timemultiplayeritisbothachallengingand
rewardingexperience.Dosomemoreresearchoutside
ofthisarticleandfindoutjusthowyourrealtime
gameneedstobestructured.Therearemanygreat
resources:GlennFiedlerhasextensiveexperienceand
generouslysharesawealthofknowledgeonthetopic.
Besuretoreadallofthearticlesonmultiplayerand
programminggamesthatruninrealtime.Hecovers
thebasicsofWhatEveryGameProgrammerNeeds
ToKnowAboutNetworking,andalsojustas
importantishisarticleanddemoonNetworked
Physics.
AnothersetofgoodarticlesarefromForrestSmith,
whoworkedontheSupremeCommanderengineat
GasPoweredGames.ThisarticleisaimedatRealtime
StrategyGames(RTS):Thefirstpart,Synchronous
RTSEnginesandaTaleofDesyncsandthesecond,
SynchronousRTSEngines2:SyncHarder.
PostedbySvenBergstrmJul18th,2012in
Multiplayer.
Tweet
Like
560
241
Share 116peoplelikethis.
Warning:
Comments
Comments
Community
Recommend 17
Login
SortbyBest
Jointhediscussion
McFunkypants 3yearsago
Thisisphenomenallyuseful,wellwritten,and
professional.Thankssomuchfortheamazing
example.I'vedonetonsoflaggyrealtimemp
usingajaxandphp,whichasyoumightimagine
isahugehassleanddoesn'tscaletomorethana
handfulofconcurrentplayers.Keepupthegreat
work!
18
Reply Share
skroob 2yearsago
Ifyouwanttogetthistoworkwithnewversion
ofnode:
app.jschange
line36
res.sendfile('index.html',{root:__dirname})
line52
res.sendfile(file,{root:__dirname})
4
Reply Share
SvenBergstrm>skroob
2yearsago
Thanks,thishasbeenupdatedintherepo
today!
1
Reply Share
PeterValdez 3yearsago
VeryinterestingreadconsideringthatImyself
usedsocket.io,node.js,andcanvastomakeapet
project(someindividual.com/grid).Notnearly
aspolishedbyanymeans,buthavingsome
multiplayernoFlashappupandrunningwasso
gratifying.
Again,greatpost!
4
Reply Share
SvenBergstrm>PeterValdez
3yearsago
Itisreallyrewardingindeed:)
1
Reply Share
Skroob 2yearsago
Gettingarathernastyerror:
TypeError:Argumentstopath.joinmustbe
strings
atf(path.js:204:15)
atObject.filter(native)
atexports.join(path.js:209:40)
atexports.send
(c:\www\game\node_modules\express\node_module
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)
atcallbacks
(c:\www\game\node_modules\express\lib\router\ind
atparam
(c:\www\game\node_modules\express\lib\router\ind
atpass
(c:\www\game\node_modules\express\lib\router\ind
atRouter._dispatch
(c:\www\game\node_modules\express\lib\router\ind
0:5)
2
Reply Share
SvenBergstrm>Skroob
2yearsago
Thiswasfixedintherepoaswell,itwas
justachangetothewaythepathwas
handedin.
Reply Share
PrashantOnkar>Sven
Bergstrm ayearago
HiSven,Iamgettingthesame
error.Canyoutellmewhatsthefix
please?Iamnewtothissite.
Reply Share
SvenBergstrm>
PrashantOnkar
ayearago
Youmightbelookingfor
thischangespecifically?
https://github.com/underscored.
Ifyouhavethecodefrom
therepo,itwould
automaticallybeinthe
latestcode,unless
somethinghaschanged
sincebutnobodyhas
reportedanyissuessofar.
Reply Share
eldad87>Skroob 2yearsago
I'mgettingthesamething.
Reply Share
SvenBergstrm>eldad87
2yearsago
seecommentabove:)
Reply Share
MiguelRipoll 2yearsago
Thisarticlehelpedmealot,thanks!
1
Reply Share
Genkikami 2yearsago
OkaysoIamtryingtojustuseyourtutorialfor
settingupthebasicwebserver.SoIcopiedthe
expressandsocket.iocodenearthetopintothe
samefile(app.js)andtheonlythingIchangedis
theline:
res.sendfile(__dirname+'/index.html')
ThenwhenIcompiledtheprogramonmy
commandlinewith"nodeapp.js".Itcompilesbut
assoonItrytoconnecttotheserverthroughmy
"localhost:4004"Igottheerror"Error:
ENOENT,stat
'....\node_modules\socket.io\socket.io.js".I
changedthepathintheindex.htmlfilethatI
sendfromtheservertobe:
<scripttype="text/javascript"
src="/node_modules/socket.io/lib/socket.io.js">
</script>
Butthisresultsinthiserrorinmywebbrowser
console:
SobasicallyistheresomethingbigthatIam
missing?Suggestionswelcome:).
UncaughtReferenceError:requireisnotdefined
socket.io.js:12
UncaughtReferenceError:ioisnotdefined
localhost/:26
1
Reply Share
Genkikami>Genkikami 2yearsago
Okaysoigotitworkingineededto
changethestartercodefortheserverin
orderforittowork:
var
http=require('http'),
server=http.createServer(app)
Bothoftheseneededtobeaddedand
thenchangetheline:
app.listen(gameport)
to
server.listen(gameport)
andchangetheline:
varsio=io.listen(app)
to
varsio=io.listen(server)
Theneverythingcompiledfineandran
withnoerrorsinthebrowser.
1
Reply Share
SvenBergstrm>Genkikami
2yearsago
Thanksbtw,forcommenting.This
wasupdatedintherepotoday,but
hadbeeninthepullrequestsfora
whileIhadjustbeenoccupied
elsewhere.
Reply Share
AsadMemon 2yearsago
Iamworkingonaddingsupporttomorethan
twoplayerstothisproject.
Feelfreetocheckit.
https://github.com/asadlionpk/...
1
Reply Share
Colton>AsadMemon 10monthsago
I'mgettinganerrorfromyourproject:
TypeError:Argumentstopath.joinmust
bestrings
atf(path.js..)
...
AndIamnotseeingafix.Anyideas?
Reply Share
Divyanshu 2yearsago
CanSomeonepleasetellme,whereandhowto
learnnode.jsorserver.io,asisearchedalot
thereisnotevenasinglegoodtutorialtostart
withthebeginning,shouldihavetobuyabook?
Ifsopleasesuggestagoodbook!
Reallyneedtocheckthesefeatures,thanksin
advance!!:)
1
Reply Share
Abhi 2yearsago
thisisbrilliant,thankyou
1
Reply Share
DushanNedelkovich 2yearsago
demolinkisnotworking:(
1
Reply Share
incompl>DushanNedelkovich
2yearsago
Ifixedthelink,thanksforpointingthis
out!
Reply Share
Frowz>incompl 2yearsago
Veryinteresting,ilearningnode.js
orserver.io,keepupthegreat
work!
Reply Share
SvenBergstrm>DushanNedelkovich
2yearsago
http://underscorediscovery.aws...
Reply Share
Sandy 3yearsago
learnalot,Thanks
1
Reply Share
GlennFiedler 3yearsago
Averywellwrittenarticle.Goodjob!
1
Reply Share
FlorianBsch 3yearsago
Noteacoupleofthings:
1)You*have*toconfiguresocket.iotouse
websocketsonly,orit'lltrytofallbacktoXHRsor
JSONP,whichare(asyoudescribed)woefully
inadequateforanythingapproachingrealtime
communication.
2)WebSocketsarebasedonTPC/IP,whichwhile
goodandreliable,isnotaveryfastprotocoland
itusuallyincursuptomultiplesecondsoflatency
whengoinglongerdistances(syn,ack,ack,syn,
etc.).
3)UDPwouldbemoresuitableforgames,
howeverbrowsersdonotsupportthatyet.
4)However,WebRTCisaddinganunreliable
dgramchanneltoit'sprotocol,whichis,
effectively,UDP.Thisisexpectedtolandinlate
2012
1
Reply Share
SvenBergstrm>FlorianBsch
3yearsago
Yep!Iamconfidentthatsocket.iowill
makeadditionalsupportforthattoo!
Websocketsaredefinitelythebestoption,
thoughforlessinstantaneousgamesyou
couldeasilyfallbacksafely.
1
Reply Share
Angelblade 3yearsago
Amazing,wonderful,thankyousomuch
1
Reply Share
realUser404 3monthsago
Toobadmanypartsofthecodearedeprecated
now
Reply Share
Lucidbrot 3monthsago
res.sendfileisdeprecatedyoushouldnowuse
res.sendFileinstead
Reply Share
thegreat1200 3monthsago
HowwouldIaddusernamesandchat(with
commands)?
Also,canIhavemorethan2playersconnected
tothesameroom/server?Icanonlyget2to
connect.
Reply Share
HaseebAhmad 8monthsago
I'mplanningtomakeBrowserbasedmultiplayer
gameasafinalprojectinBSComputerScience.
Thisarticlewasveryhelpful.Formyproject,I'm
thinkingjavascriptforclientsideandjavaas
serverside.
Ifyoucouldsuggestsomearticleoranythingfor
myproject,thatwouldbeverynice.
Reply Share
MnhM ayearago
Thisarticleissouseful,thankyouverymuch
Reply Share
RickS ayearago
node.jsisverypoorlydocumentedfornewusers.
Onlinetutorialsareevenworsewhenexplaining
howtouseit'sI/OandSockets
Edit:donotevenbotherwiththisThereareno
(good)webhoststhathassocket.io,node.jsor
express.jssupport.
IfyouhavetheenergyandtimetofightAmazon
hostingbemyguest.I'llsticktoJava.
Reply Share
swifton>RickS 4monthsago
Whataboutheroku?Isn'tthatagoodweb
host?
Reply Share
Mane>RickS ayearago
Yes,Iagree,node.jsdocumentationis
directlyjustapidocwhatitincludes,so
googlingaroundhowtouseitisfaster
thanactuallyreadingit.Andasforthe
webhosts..Whatyouaretalkingabout?
Whataboutheroku?nodejitsu(firstwith
propersocket.iosupport?)andspeaking
ofhostsandthelaginthisdemoIassume
thatitisrunningonsomefreeinstance
whichhashighlatency.BUT,Ifyouare
abouttomakeagame,settingupproper
serverwithgoodCPUandlowlatency
mightbeneededanyway..Ihaven'tdone
anycalculationsbutIfearthatthose
"dynolike"herokuetc.solutionsmight
notbeaproperwaytogo..soyou
eventuallyhavetofighttosetupgood
server)
Reply Share
RickS>Mane ayearago
Oneword:GitHub...Ican'tNOPE
loudenoughwheneverasite
declaresGetHubmandatory.
Ilivein2014,not1995.
1
Reply Share
Mane>RickS
ayearago
WhattheheckisGetHub?
1
relatedarticles
Reply Share
TeamSnake:APostMortembyDariusKazemi
OptimizingWebSocketsBandwidthbyEricLi
WebSockets:AGuidebyJackLawson
morestuff
Creatinga3DgamewithThree.jsandWebGLby
NikhilSuresh
SimulatingNaturalSystemsinaWebBrowserby
VinceAllen
MakingGamesFunbyBurakKanber
VectorFieldObstacleAvoidancebyAlexander
Sutherland
AnintroductiontotheCraftygameengineby
DarrenTorpey
Home
EditedandoperatedbyBocoup.
EditedandoperatedbyBocoup