We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

HTML5 WebSockets and Socket.IO

00:00

Formale Metadaten

Titel
HTML5 WebSockets and Socket.IO
Serientitel
Anzahl der Teile
110
Autor
Lizenz
CC-Namensnennung - keine kommerzielle Nutzung - Weitergabe unter gleichen Bedingungen 3.0 Unported:
Sie dürfen das Werk bzw. den Inhalt zu jedem legalen und nicht-kommerziellen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen und das Werk bzw. diesen Inhalt auch in veränderter Form nur unter den Bedingungen dieser Lizenz weitergeben
Identifikatoren
Herausgeber
Erscheinungsjahr
Sprache

Inhaltliche Metadaten

Fachgebiet
Genre
Abstract
The web is no longer about retrieving documents interlinked to each other, as it was envisioned decades ago. With the explosion of the Web 2.0, AJAX led the way towards efficient communication and just retrieving or sending what was necessary. HTML5 introduces a new range of APIs that make the creation of full-fledged interactive applications easier than ever. With that comes WebSocket, which exposes a very basic channel of bi-directional communication with little overhead. WebSocket enables the transmission of data in real time faster and easier than ever before. Projects like Socket.IO, subject of this talk, have been working hard on bringing this API to everyone, in the same way jQuery did for the DOM and AJAX. Not only do we make WebSocket ready for real-world usage, but it comes with fallbacks for every browser. This talk will explore the creation and deployment of a realtime application the audience can interact with from their laptops and mobile devices.
23
63
77
Protokoll <Datenverarbeitungssystem>SoftwareentwicklerWeb SiteServerEchtzeitsystemExogene VariableWeb logGraphfärbungMessage-PassingDemo <Programm>Treiber <Programm>Projektive EbeneFramework <Informatik>Streaming <Kommunikationstechnik>SpeicherbereichsnetzwerkSelbst organisierendes SystemVersionsverwaltungPROMBrowserProtokoll <Datenverarbeitungssystem>PunktAutomatische DifferentiationWärmeübergangSoftwareentwicklerGoogolSocketZahlenbereichImplementierungProdukt <Mathematik>DifferenteTropfenDienst <Informatik>BitAggregatzustandOpen SourceBenutzerbeteiligungEndliche ModelltheorieMathematikComputersicherheitWort <Informatik>LastSocket-SchnittstelleBinärcodeWhiteboardProzess <Informatik>Güte der AnpassungAdressraumUmwandlungsenthalpieFamilie <Mathematik>Graphische BenutzeroberflächeDatensatzAutorisierungFront-End <Software>Twitter <Softwareplattform>Fluss <Mathematik>EinsLastteilungEin-AusgabeSpeicherabzugApp <Programm>ClientDreiecksfreier GraphComputeranimation
Gesetz <Physik>SoftwareentwicklerArithmetischer AusdruckInstallation <Informatik>HydrostatikFunktion <Mathematik>ServerSpielkonsoleEinfach zusammenhängender RaumIndexberechnungSkriptspracheSocketMessage-PassingMehrrechnersystemStellenringInnerer PunktVisuelles SystemGeradeWeb SiteBrowserMessage-PassingEinfach zusammenhängender RaumServerPatch <Software>Weg <Topologie>BeobachtungsstudieSoftwaretestKreisbewegungTelekommunikationZellularer AutomatSocketProjektive EbeneGüte der AnpassungEndliche ModelltheorieGraphische BenutzeroberflächeMailing-ListeApp <Programm>BimodulEreignishorizontMiddlewareHydrostatikElement <Gruppentheorie>Abgeschlossene MengeVerzeichnisdienstOffene MengeDomain <Netzwerk>Computeranimation
ServerSoftwareentwicklerSocketSpielkonsoleFunktion <Mathematik>Einfach zusammenhängender RaumMessage-PassingStellenringLogarithmusMehrrechnersystemHydrostatikHeegaard-ZerlegungDienst <Informatik>MAPEinfach zusammenhängender RaumAbstraktionsebeneAlgebraisch abgeschlossener KörperOffene MengeMessage-PassingLeistung <Physik>SocketSpieltheorieMotion CapturingGoogolClientEchtzeitsystemWeb SiteTelekommunikationServerImplementierungDemo <Programm>Computeranimation
ServerSoftwareentwicklerSystemplattformSocketMAPAbstraktionsebeneServerSocketWeb SiteRechenschieberBrennen <Datenverarbeitung>SoftwareentwicklerAdditionSchnelltasteTouchscreenLeistung <Physik>MultiplikationWeb-DesignerSpieltheorieEreignishorizontBrowserImplementierungMultiplikationsoperatorMathematikZentrische StreckungComputeranimation
SoftwareentwicklerProgrammbibliothekSicherungskopieGoogolSkriptsprachePrototypingFunktion <Mathematik>MultitaskingSystemaufrufImplementierungTouchscreenTermCodeEin-AusgabeRechter WinkelComputeranimation
SoftwareentwicklerFunktion <Mathematik>PrototypingPrimzahlzwillingeSchlüsselverwaltungSystemaufrufMathematikMultitaskingEgo-ShooterSpieltheorieSocketPartikelsystemCachingSnake <Bildverarbeitung>FarbverwaltungssystemMarketinginformationssystemSystemaufrufBitrateBildverstehenCASE <Informatik>Message-PassingEinfach zusammenhängender RaumZeichenketteEreignishorizontRPCFunktionalSocketArithmetischer AusdruckProzess <Informatik>GruppenoperationProjektive EbeneBenutzerbeteiligungPuffer <Netzplantechnik>Produkt <Mathematik>SchnelltasteAddition
SocketKonfigurationsdatenbankFaser <Mathematik>MaßerweiterungSoftwareentwicklerArithmetischer AusdruckAppletFunktion <Mathematik>CAN-BusHydrostatikSkriptspracheServerVerzeichnisdienstBimodulLastteilungFunktionalVarianzApp <Programm>CASE <Informatik>Elektronische PublikationEinfach zusammenhängender RaumSocketSocket-SchnittstelleSoftwaretestTypentheorieKartesische KoordinatenMathematikAliasingDifferenteZahlenbereichBenutzerbeteiligungVersionsverwaltungAdditionMultiplikationsoperatorRechenschieberServerInstallation <Informatik>Codesinc-FunktionGüte der AnpassungPunktHeegaard-ZerlegungHydrostatikSystemprogrammProgrammbibliothekProjektive EbeneOrdnung <Mathematik>Message-PassingCoxeter-GruppeEndliche ModelltheorieFlash-SpeicherWort <Informatik>Rechter WinkelVererbungshierarchieComputervirusZellulares neuronales NetzProxy ServerFehlertoleranzSystemaufrufBeobachtungsstudieURLWeb SiteComputeranimation
SoftwareentwicklerClientHackerFächer <Mathematik>ServerHydrostatikSchlüsselverwaltungTOEFunktion <Mathematik>PrototypingSystemaufrufRechenwerkSocketEgo-ShooterMathematikFontSpieltheorieMAPDruckverlaufSocketThreadCoxeter-Gruppep-BlockMultiplikationsoperatorSocket-SchnittstelleEreignishorizontStichprobenumfangEinfach zusammenhängender RaumCASE <Informatik>Puffer <Netzplantechnik>SpieltheorieServerFunktionalRückkopplungSystemaufrufLesen <Datenverarbeitung>Heegaard-ZerlegungWhiteboardComputeranimationProgramm/Quellcode
ZeitzoneGammafunktionEgo-ShooterSocketFunktion <Mathematik>Fächer <Mathematik>Maskierung <Informatik>Finite-Elemente-MethodeSoftwareentwicklerMotion CapturingVektorraumWeg <Topologie>Objekt <Kategorie>RichtungOrtsoperatorVariableSpieltheorieWort <Informatik>AggregatzustandVollständiger VerbandKonstruktor <Informatik>Computeranimation
Fächer <Mathematik>SoftwareentwicklerFunktion <Mathematik>Kinetische GastheorieSchlussregelElement <Gruppentheorie>SpieltheorieSystemaufrufComputeranimation
Metropolitan area networkGesetz <Physik>Funktion <Mathematik>Inklusion <Mathematik>SoftwareentwicklerSoftwaretestLemma <Logik>HMS <Fertigung>Formation <Mathematik>Konvexe HülleMultiplikationsoperatorZweiElement <Gruppentheorie>Minkowski-MetrikEreignishorizontRechter WinkelDemo <Programm>Computeranimation
DatentypFächer <Mathematik>SchlüsselverwaltungSpezialrechnerDruckverlaufFunktion <Mathematik>SoftwareentwicklerPrimzahlzwillingeMUDInklusion <Mathematik>RechenwerkKontextbezogenes SystemOrtsoperatorElement <Gruppentheorie>ProgrammierstilComputeranimation
SoftwareentwicklerFunktion <Mathematik>SCI <Informatik>MIDI <Musikelektronik>MathematikSoftwaretestSpezialrechnerInklusion <Mathematik>VakuumHMS <Fertigung>Elektronisches ForumSimulated annealingZellularer AutomatStrebeMenütechnikMathematikEntscheidungstheorieOrtsoperatorRichtungArithmetisches MittelWeg <Topologie>TeilbarkeitSchnittmengeEreignishorizontServerPerspektiveObjekt <Kategorie>Computeranimation
MenütechnikFunktion <Mathematik>SoftwareentwicklerRechenwerkInklusion <Mathematik>SocketSpielkonsoleSkriptspracheSpieltheorieObjekt <Kategorie>OrtsoperatorZeitstempelPerspektiveDigitalisierungGüte der AnpassungMathematikRichtungRechter WinkelWeb-SeiteGeschwindigkeitCASE <Informatik>Freier ParameterVektorraumMultiplikationsoperatorEntscheidungstheorieStrömungsrichtungSelbst organisierendes SystemGruppenoperationComputeranimation
BimodulFunktion <Mathematik>SocketSpielkonsoleSoftwareentwicklerGesetz <Physik>Fächer <Mathematik>LogarithmusSoftwaretestClientInhalt <Mathematik>Lokales MinimumHydrostatikTrägheitsmomentHackerMechatronikNormierter RaumPlot <Graphische Darstellung>SchlussregelGruppenoperationDifferenteRückkopplungDefaultServerOrtsoperatorMultiplikationsoperatorBaum <Mathematik>PerspektiveEreignishorizontDatensatzComputeranimationProgramm/Quellcode
Funktion <Mathematik>SoftwareentwicklerDatenflussplanSocketFehlermeldungSpielkonsoleLogarithmusWiener-Hopf-GleichungSoftwaretestDatenverarbeitungssystemSpieltheorieObjekt <Kategorie>Nichtlineares GleichungssystemDatenstrukturDifferenteAggregatzustandWeg <Topologie>OrtsoperatorFahne <Mathematik>EreignishorizontEinfach zusammenhängender RaumCASE <Informatik>RichtungGrundsätze ordnungsmäßiger DatenverarbeitungBroadcastingverfahrenBildschirmfenster
Funktion <Mathematik>LogarithmusSpielkonsoleSoftwareentwicklerSoftwaretestSchlüsselverwaltungNormierter RaumGruppenoperationLochkarteSocketRechenwerkFächer <Mathematik>CASE <Informatik>Rechter WinkelParametersystemMathematikComputeranimation
SoftwaretestSoftwareentwicklerBrennen <Datenverarbeitung>Funktion <Mathematik>SchlüsselverwaltungGesetz <Physik>QuantenzustandKlon <Mathematik>ClientElektronisches ForumHydrostatikRechenwerkMachsches PrinzipDoS-AttackeAggregatzustandMathematikOrtsoperatorEreignishorizontResultanteMereologieWeb-SeiteMechanismus-Design-TheorieComputeranimationProgramm/Quellcode
Funktion <Mathematik>SpielkonsoleSchlüsselverwaltungMachsches PrinzipSoftwareentwicklerRFIDAnwendungssoftwareSocket-SchnittstelleTaupunktHoaxDoS-AttackeBroadcastingverfahrenSocketWeb-SeiteOrtsoperatorEreignishorizontPackprogrammMereologieMathematikRichtungBroadcastingverfahrenMittelwertTypentheorieEntscheidungstheorieWeb Site
SoftwareentwicklerHydrostatikSocketClientInhalt <Mathematik>Funktion <Mathematik>RechenwerkKonvexe HülleSpieltheorieComputeranimation
Funktion <Mathematik>SocketKorrelationSLAM-VerfahrenSoftwareentwicklerSoftwaretestEreignishorizontMultiplikationsoperatorComputeranimation
Funktion <Mathematik>ZustandsdichteSechseckSocketDigital Object IdentifierDatentypEbeneFächer <Mathematik>KorrelationNormierter RaumKonvexe HülleSoftwareentwicklerSchlüsselverwaltungRFIDDoS-AttackeARM <Computerarchitektur>Rechter WinkelMultiplikationsoperatorNebenbedingungDifferenteForcingComputeranimation
SoftwareentwicklerARM <Computerarchitektur>Disk-ArrayMakrobefehlURNSystemprogrammSystemaufrufCodeSpieltheorieElektronische PublikationComputerunterstützte ÜbersetzungSocketWeb SiteComputeranimation
PROMVerhandlungs-InformationssystemStatistikRankingInnerer PunktEgo-ShooterAppletSoftwareentwicklerMereologieIndexberechnungNatürliche ZahlFunktion <Mathematik>SocketMakrobefehlVersionsverwaltungWeb SiteSpieltheorieEinbettung <Mathematik>Prozess <Informatik>Geneigte EbeneImplementierungLesezeichen <Internet>SystemprogrammProgramm/QuellcodeComputeranimation
Fächer <Mathematik>SoftwareentwicklerRechenwerkLesezeichen <Internet>Computeranimation
SoftwareentwicklerFächer <Mathematik>NewsletterMenütechnikLesezeichen <Internet>Graphische BenutzeroberflächeWeb SiteSocketDemo <Programm>Rechter WinkelComputeranimationProgramm/Quellcode
SoftwareentwicklerSocketDesintegration <Mathematik>DatenverarbeitungssystemWeb SiteSpieltheorieFreier ParameterAbgeschlossene MengeSocketProzess <Informatik>Virtuelle MaschineProgram SlicingPunktRechter WinkelWort <Informatik>FunktionalSommerzeitStrömungsrichtungIntegralWeb SiteGraphfärbungRechenschieberVersionsverwaltungSpeicherabzugComputeranimation
SoftwareentwicklerMessage-PassingMultiplikationsoperatorSocket-SchnittstelleComputersicherheitServiceorientierte ArchitekturQuick-SortServerPeer-to-Peer-NetzSocketComputeranimation
Transkript: Englisch(automatisch erzeugt)
I'm gonna talk about pretty much the same thing but with a very specific difference so yesterday I talked about the rise of server-side JavaScript today I'm gonna talk in specifically about one of the things that was a core idea that I conveyed yesterday which is server-side JavaScript is
great for the real-time web and today we're gonna be talking about the real-time web exactly we're gonna be talking about HTML5 web sockets and how basically you're gonna implement them how you can leverage two projects websocket.io and socket.io and for those of you who have more experience or
are more interested in socket.io I'm gonna be talking about a little bit of the state of the project and the upcoming 1.0 release which is gonna happen really soon and some of the new stuff that has not been shared before and you're gonna have the first exclusive peek at the new stuff so for
this those of you who don't know me I'm Guillermo Rauch on Twitter you can find me by at RauchG or my blog devsauce.com I'm the CTO and co-founder of a company called LearnBoost we're based in San Francisco and we're basically trying to change the world of education through technology I started
my career in open source many years ago working for the mood tools front-end JavaScript framework but lately I've been doing a lot of server-side as well and I ended up creating something called socket.io which I'm gonna be
showing today and we're gonna be writing a little project with it and a few other less interesting stuff but still useful like MongoDB's drivers and tools and a few other things that I'm gonna use today during the demo like how do you make sure you can transfer web socket traffic or do long polling
requests and make sure that you can still reload your server and do sticky load balancing. I'm also the author of a book called Smashing Node this is a second day in a row that I'm plugging it but it's really useful if
you are just getting started with Node.js so if you are buy it and well today we're going to talk about HTML5 web sockets for those of you who are not who haven't heard of them or you're not sure how to use them or how they're useful I'm gonna do a little introduction to what they are what's the state of web sockets today pretty much like any other HTML5
technologies it's in flux there's a lot of changes that happen to it there is new stuff there is new stuff that's being added to HTML5 that is correlated to web sockets like the new WebRTC APIs for doing camera and audio transfer and then of course I'm going to be talking about Socket.IO
and Socket.IO 1.0 so that's a lot for an hour Wow so let's get started with web sockets. WebSocket is basically a protocol and the best way to summarize it is that it's TCP for the web it's
encoded and formalized as the RFC 6455 and the counterpart to the protocol is that when we implement it on the browser we're basically just using an API so WebSocket is also an API of course which basically allows you to send and get messages in real time really fast and lately like I said it's
not just messages the WebSocket protocol is also about sending streams of binary data so that's also where Socket.IO is going to help us quite a bit especially as these APIs like I said become more popular and ready to
use so like everything else that's new and really interesting and really hot like web sockets it comes with we have some problems today in their implementations so problem number one numero uno we have different protocols
implemented in different browsers today so during the creation of WebSocket which started at Google a number of maybe like longer than a year now it basically started as a draft and it evolved incrementally with different revisions to this draft at one point it was at draft 75 and they were like
okay so this is this is good enough to implement it doesn't matter if it crashes a few websites or if it's insecure we're gonna implement it so what happened is browsers did implement it right away but for example Safari which is a browser is known to have slower releases release cycles ended up
implementing that as draft 75 or 76 and they stuck with it so today the only browser that is like really up-to-date with with WebSocket is Chrome and surprisingly to a good guy IE10 so IE10 has a developer preview which has up-to-date WebSocket support with a few minor glitches that
sock.io addresses as well and as far as the other devices or web browsers are concerned we have iOS 4.2 and app boards has WebSocket but it has the older less secure version so these drafts that I was talking about they
have some security concerns and they are implemented today in these three browsers so as far as Firefox goes they are pretty much up-to-date but they call it Moz WebSocket so if you guys are used to seeing CSS prefixes everywhere now we have a few API's with prefixes as well so we have a
panorama where there is different protocols out there the good thing is those protocols can be seamlessly implemented which means you can have a server that responds to requests and to basically user agents that have all these different WebSocket versions so there's a project that I created
called WebSocket.io so the job of WebSocket.io is to give you this really reliable WebSocket implementation and WebSocket.io sits on top of another project by Norway's own Einar Otto which is called WS and that's a
terrific and the fastest WebSocket server and client implementation it's blazing fast so before I move on I want to show you guys how to implement WebSocket.io really quick in Node.js so I'm
gonna create a project called
WebSocket so the first thing we do is install WebSocket.io I think that was the name they published it to NPM with and Express which is the
HTTP server that I always use to just serve some HTML we don't really my neck is gonna hurt afterwards so I'm gonna create an app I'm gonna do
I do this every day I do a static middleware I'm gonna create the
directory and then I'm gonna serve some basic HTML no actually I'm gonna have static server never mind so I'm gonna attach WebSocket.io so one thing that's really important is WebSocket can coexist alongside your
HTTP server you don't need to create a new host you don't need to register a new domain you don't have to do anything you can just attach it and let it handle the upgrade requests so that's exactly what I'm gonna do is I'm gonna call so and then I'm gonna make my server listen I'm gonna detect the
connections so whenever I get a connection we're gonna say that someone connected so I'm gonna do it I mean now I'm gonna say that like I said
earlier we have the client-side API for WebSocket and that's what exactly what I'm gonna implement so since I'm gonna be using Chrome I think or maybe Safari I don't need to worry about detecting whether it's there or not normally unless you're targeting a specific browser you would want to use
Moz WebSocket or WebSocket so so the WebSocket API is really simple like
I said it has three event handlers on open on close and when when we get a
message so what we're gonna do basically is send some messages back and forth to measure the latency of the connection so we're gonna track whenever we got the last message and we're gonna print that in some element
for those of you who are getting bored more exciting stuff is coming up so measuring latency is not that exciting but we're gonna show basically how easy it is to send open a channel of communication and send data back and
forth with node and WebSocket so here so whenever we get that connection
we're gonna send the user a message so we're gonna say ping whenever the user connects and whenever they get that message we're gonna send pong back so by creating that back and forth between messages we can measure how long
it's taken to create to complete that round-trip so I think this looks oh sorry this is I made that up I think I was thinking jQuery so I think we're
good for a test we'll see how it goes all right so oh I thought I was
showing the browser so right now you're gonna see that it's not actually
updating and the reason is that I forgot something so we're gonna split this so what I forgot is to capture the message we're gonna do it like this
instead oh we need to open with a message so here we're gonna say so like
you see it's it's something that's extremely fast because it's my local connection but we can see here that we've basically established something
where we can send data back and forth very easily and as much as we want and this very fundamental thing is what it's gonna empower our next demo and we're gonna be basically leveraging the power of this super fast real-time communication to actually make something useful out of it and namely a game so
just to recap really quickly we can attach a WebSocket.io it's gonna capture the connection I'm gonna send that gonna give us a closure with that and we're gonna be able to exchange messages it's very similar to how the
API looks like on the client and in fact we have hooks in there so that you could actually like do an isomorphic almost even though some people don't like that name API where the server the server handlers and the client handlers look exactly the same so that's basically all it takes nowadays
to implement WebSocket with node and the other cool thing of course is that the same is true for we we have any if we were to use a phone it would be
working seamlessly so like I said we already have fragmentation the WebSocket world sometimes it is easy to assume oh I just need a real-time socket I don't need higher level abstractions therefore I literally just throw a WebSocket server no you have to be careful which WebSocket server you're using so I'm
gonna close this I'm gonna close this too and I'm going to go back to keynote with a very exciting next slide which is wow so that was really
easy and we're gonna show that our intent with Socket.io and all these APIs is that we're gonna try to not divert away from the WebSocket API too much because unlike most of the APIs that us web developers are used to namely the DOM WebSocket is actually really good it's really simple really straightforward and most people like it but meanwhile in the real world we
like I said we do have problems with fragmentation with WebSocket but we have bigger problems than oh people have really modern browsers but I don't know which one they have is that we we have a lot of old stuff out there so for
that most of you are familiar with my solution which is Socket.io so for those of you that are not so familiar with Socket.io or how to use it I prepared a I was thinking this morning so what what can I do that shows the power of Socket.io and the power of WebSocket and it's like really
interactive and cool so what I came up with I stole an implementation of Asteroids that's really cool that has a specific twist and I made it multi-user so basically I took everything that would assume that there is only one player in the screen and I changed that so that it would
support multiple players and in addition I did some other stuff so that it would be easy to receive events through Socket.io and convey them to the game without assuming that there is a keyboard in there so I'm gonna go over
the initial implementation of this basically our first goal is going to be to like show to little players on the screen so I'm gonna so we're back with
I term okay do you guys see the text well or should I is okay so we're gonna be doing the same thing but I'm gonna quickly show you the code for the oh
wow that's huge so I had to add this for I had forgotten that iOS doesn't have function product I bind so this is my addition as well this
project is really neat this has been created by a guy called Erky and well here we have the constructor for for the asteroids what do we consider the asteroids in this case is just the arena with the player so whenever we initialize an asteroids object we're getting the whole thing and we're
actually not getting asteroids we're getting just it's just a spaceship so oh what call it spaceship we're gonna call it asteroids so like I said the first thing we want to do is actually implement socket.io so we're gonna connect I'm gonna show you later how socket.io comes into the
picture where it pops up from but basically we just want to do io dot connect actually I don't want to write this and then I want to do I normally don't do this but today I want to do this I want to listen on the connect event so normally you don't need to listen on the connect event because
whatever you do socket.io buffers and sends later so like if you start sending data right away unlike the web socket example that I showed earlier if you start writing to the socket it's buffered and when you connect it's sent out so but in this case I do want to and and the reason is I want
to ask the player who is who's what he's called so and only I want to actually I'm gonna do that outside sorry because of reconnections so I'm gonna ask the user like what is your name then whenever the socket opens I'm
gonna send back that name and rotate again so that's what I'm gonna do
so unlike web socket here I'm almost like naming my messages so in socket.io I'm not doing socket dot send and something I'm doing socket emit so I'm sending a remote event and whatever I tag along with that remote event is JSON encoded so in this case I'm gonna send the name of the player it's gonna
be a string in this case so sorry but once again I probably want to install socket.io and express I should have an alias for that NPM install sexpress
anyways gets installed goes into the node modules directory same deal but now
I'm gonna require socket.io once again the cool thing is we're making this API is really similar to so when you attach a web socket server in this case socket.io is gonna listen on it we're gonna create the socket.io listener and
we're gonna listen on connections so first difference with web socket.io we have this sockets stuff here why we have it's because with socket.io you can
connect multiple sockets and they get multiplexed so you could say I want to connect to slash something or I want to connect to slash something different and those you could capture as if as if they were actual different sockets although for version 1.0 where you're gonna be able to do this so it's
gonna actually proxy it through the alias of sockets but this is gonna be one difference for those who are familiar with the API it's gonna be more straightforward and in addition another another difference that both I express and socket.io are getting another changes we realized most modules should
only just expose one piece of functionality so in order to create an express application you go like this in order to create a socket.io listener you go like that so that's gonna be all the initialization need to do so
that's not really relevant or important but it's neat for those who type io.sockets a lot in presentations. So we're gonna hear it get once again say okay user connected for a quick test sanity check that's a column and I want
to serve some static files I'm gonna listen on so one thing I'm gonna
show you that's really cool is when you create a node application and you find yourself reloading it all the time I'm gonna show you a little trick so I'm gonna listen only if module.parent is not defined and and I'm gonna
export here the app so for those of you who are really into CoffeeScript or hate the var keyword you're gonna notice that I never prefix app with a var keyword and the reason is that usually there's only one app in my entire app obviously so when you have big projects with tons of files it's
usually useful to have that app floating around you could argue it's a hack but it's neat so I think we're good I'm gonna create static again and here the only difference between just using web socket really and using
socket.io is like I'm gonna need to include the library but we make it really easy to do so so I'm gonna call this socket.io asteroids and good point
I'm gonna move asteroids in there I know lots of you have iPhones I have
an iPhone too so I already created a little way of controlling it through your phone once we start showing the demo and that once again is gonna get served hopefully by static so here's here goes the trick that I mentioned earlier so instead of noting that server which is gonna listen on port
3000 which by the way I redirect my port 3000 to port 80 so I don't need higher privileges so and that would mean that every time I get changed I have to reload the thing so what I do is I create that utility if you remember from slide number four called up so up you pass watch it watches the
directory and then you pass server so it spawns workers that get replaced on the fly whenever there's a change and this is where long polling comes in really handy even even though web socket is cool with long polling since we're splitting requests most load balancers are already already know how to buffer
and split requests in a keep-alive connection whereas if you want to reload your code for a web socket it would be slightly more complicated you would have to drop the user with up and solutions like this you don't really need to drop any requests at all we buffer the request until the new worker is up so so user connected one thing that you might have noticed is
see there the prompt is really cool for presentations because you know like I
don't know what I would do without prompt I would probably like inject a form and like add an event listener so with prompt what's happening is it's blocking the thread so never use it along with socket AO because it's gonna block everything so your sockets are gonna time out actually but for the sake of this example it's really handy so my name is Guillermo and user
connected you see that the connection actually went through afterwards even though even though it shouldn't be a case so now that we know that user can connect we're gonna go ahead and you know what actually I'm gonna split this
it's gonna be a mess otherwise let's call this game oh so my vim right now is not syncing buffers with embarrassing it's not syncing buffers
with my clipboard so I have to do this so back to the game first thing we
want to do when someone connects we want to get some feedback from the server first so I'm gonna do this little function called on me which I'm gonna have the server sent to us so vim splits are coming really handy
here even though they're like a little tight can you guys still see well yep all right I'm a reading room all right so you see here that I'm meeting name I'm gonna capture a name here so what I want to do when when
someone actually starts the game which means that they're sending me their name is keep track of a few things so I'm gonna keep track of how many players
we've got and I'm gonna keep a state object of basically what I'm gonna consider my room so I'm gonna keep a state object of everyone that's in the game floating around where they are etc so when when we get a name I want to first consider that there is a new player then I want to do some like I
said object that keeps the player position another thing that this game has in particular is like we have a vector that determines that the
have a vector that it that has a direction so we have the position and the direction so before actually I move forward with that I'm gonna show you what the single-player stuff looks like so so here I'm gonna so that
uppercase variable is not mine this is not gonna be public once again we're
committing so many ugly JavaScript style stuff that forget that we're doing stuff like this so I added a few things to the asterisk constructor like
starting position and a starting direction and then handlers for where the things move or we get we fire something so I'm gonna label my guy with name alright so I think that should be enough let's go to that
another tab actually can't see so something went wrong oh no oh I'm not I
think I'm not including game yeah too bad so you know what's cool I'm gonna add like a title and call it asterisk.io do you think someone knows
that oh you know what it is so it's telling me I have no elements that's
funny I had never come across that Wow so this is the player like I
described now the thing here is when you you can fire elements so when we do the demo we're gonna go to ndcoslo.com and we're gonna fire everything and so I predicted that people would get really crazy so what I did is I'm throttling the spacebar event to 10 seconds so you're not gonna
be able to remove everything like you could hold a spacebar and like remove everything right so we're not gonna allow that also interesting is that we're gonna need names so let me think so we probably want to identify
those guys again this code style is not mine I'm very very particular about it
okay so when we draw the player this is the canvas context so for those of
you who are not familiar with canvas I found out this I found this out yesterday but apparently when when when you call one of these handlers actually I don't know how this guy is doing it but when he calls this handler this is
bound to the to the context which is really handy so we want to do a fill text with the label of the guy and see here we're translating the element sorry the path to that position so we're gonna simply alright so I think we can
make it look better so I just mistyped my name so moving forward we want to do
is we want to assign a label to each of these players and we're gonna do so by initializing players when so first of all we want to initialize our own
player from the server perspective from the server perspective we want to give this guy a initial position that's random so we were gonna say that Y Y is a hundred and we're gonna expect expect that the server gives us
a position and also an ID so let's tell this guy so first of all we want to save down that idea around we could technically use the session ID that soccer you gives you but you don't want it you don't want to do that it's
private so we we give this guy an ID and we send it back with the me event once again me see it there me and me so we give him the ID and
we're gonna give him the actually we're gonna give him the player object so in this player and we want to keep track of the name we're gonna keep track like a set of direction oh so I got distracted so this is the direction stuff
that I was talking about so there's two vectors that we care about mostly there's actually four but we want to care about position and we want to care about direction we could care about velocity so for example if you're moving around and then someone refreshes the page you would get his existing velocity that would be cool but not not for this not for this case so
direction is also determined by a XY so for X we want to create something random so again the idea you came up with for this is you take the you
take the current timestamp and you take the last three digits and it's gonna be a number under under a thousand so that's cool and for Y want to do a hundred actually so we have the direction we don't want to we
don't really care about now but we're gonna leave it a placeholder and then we're gonna send back the player object and I think that's all we need
to initialize oh and we also want to capture changes for these guys so whenever they change position or they fire I think I called it fire so
whenever someone fires or changes their position we want to relay that so this is looking pretty good that's not looking good I need to the perspective
is killing me oh it's actually good right yeah I think so so let's see
all right that's me so the difference here is I'm getting feedback from the server so a lot of people hate this but so get a oh by default is like
overly verbose but it's cool because like you know it's actually you're actually getting stuff here oh and see saw I think that worked yeah that worked did it work no it didn't work so technically we should be getting a position here but I think it's defaulting to the same every time oh yeah
thanks so I guess undefined is defaulting to something yeah cool boom so
now that we have this player going we also want to get other players so how do we get other players what do we want to do when someone connects is broadcast that player to the other people so we're gonna define a here we're gonna I'm having perspective issues again all right so we want to
capture a player event so here we're gonna have again an ID and like a
player object and here we want to keep track of the players so whenever I
actually create a new asteroids object and this is where it gets more interesting so in this case we do want to keep track of the initial
position and direction because like I said you can start off in a different direction so I call that their X so when yeah like I said whenever someone
connects we're gonna basically have him appear and for that to happen on the other side of the equation thanks nice catch so here like I said we want
to we got a new player we want to broadcast it to everyone else that we have a new player so we if we add this flag which basically takes something and sends it to everyone else so we're gonna send that player guy and when I attach the ad so the difference here is that everyone else
is gonna get that event not not that one player so if everything is good we should now have be keeping track of players one thing that's important is that when someone disconnects if they had a an ID we want to destroy that
guy sorry and we want to emit that that guy disconnected let's call it
so on the other side of the equation if we have that we have player remove
we're gonna basically call a destroy method on it so it gets rid of the canvas stuff and then we want to delete that stuff also notable is when
someone connects we want to give them the existing players so not just a broadcasting to everyone else but you want to get the stuff that's already
there which is in the players object here so what we do is we walk it I think I don't need to check and we meet for that one guy we meet player events this is similar to like if they were connecting as new guys but they were
already there and that's where it's important that I'm gonna also keep the here that's why it's important that we we structure this around events because
there could be existing state or there could be new but for the sake of the game it doesn't matter oh wow something's going on there all right so that's me I'm gonna have window problems here so I'm not getting
the other guy but oh wow oh is it oh oh oh yeah oh I'm moving two guys here oh
you know why cuz so that's the other thing I realized if this game is already a single player you could potentially move everyone we don't want that so Keith's fault oh it's this guy's here oh well that's not so bad
I'm not sure what's going on there's like a hundred players but I'll take it
for now so okay so next thing we want to do is capture that people are firing and doing stuff right so we go here on change I don't remember the arguments that I get I think I just saw them actually let's let's give this a nice
restart I'm having so many state issues so let's see all right so on
change is giving me the so this is interesting what I'm gonna do is just relay the basically the events that the guy is firing and this is a problem because like you usually want to have some like latency compensation mechanism so you don't want to send every movement that everyone is doing
but you're gonna notice that as we do this you're there's probably some lag or like someone else is lagging behind but the idea I came up with is that when you fire you do relay the exact position so when everyone is floating around it doesn't matter if everyone sees exactly where you expect them to
be but when they fire it's important they're exactly where they want to be because if they want to get riffs a specific part of the page we should let them so when we get that on change I'm gonna swap them here because I can see stuff when we get on change here I'm gonna say player move and I'm gonna
send my ID which is ID and I'm gonna send the so when we get a sorry so
so when we get player move event we just want to relay it so we just want everyone else to get it and we want to archive the position too so that if you
refresh the page you get it but we don't want to relay that to everyone else because it would be like super high traffic so we also want to oh you
know here we're gonna have some problem let's go the asteroid so we want to
update the direction and and position and when here we are gonna broadcast it
so players ID we want to update the position and we have the direction so
I think we're good here so let's see if it works yeah probably hold on
cuz we have one here too here and where do I have the other one well this thing should be telling me right where is it oh thank you all right so
oh and I think I'm sending myself so let's see if if you're getting well
we're getting the event so now we have to capture it here so whenever the player moves we want to find him oh we're pretty tight on time so okay all
right so you can see there that the player is getting their movements relayed and oh we're having a name issue I think yeah so it's it's getting
called as the same guy so basically when someone fires we want to do pretty much the same thing the difference is that let's see so due to time
constraints I'm gonna speed this up by giving you guys an URL where I deploy
this earlier so here it should be force fire equals true so what I did after I completed all this code is I used there's an utility called I can
remember now there's an utility called book boo that will generate a book Marlette so the idea is that we want to compress soccer do and the asteroids game into one file that you can copy and paste so you would basically do JS oh sorry and then you would cat the game and then you would
cat socket ao into it so once we have the book Marlette you simply run
the book boo and what this gives you is something that you can copy and paste and add to any website so notice that here in my game I'm connecting to
my own host the idea is that if you're embedding this on any website you would want to connect to wherever we deploy it we deployed it so what I did is oh I deployed it so yesterday people were asking me how do you deploy
this stuff and it's really simple so sorry you can you have an utility node
called jitsu is provided by no jitsu basically what you do is called jitsu dot and you follow this process sorry jitsu deploy and once you follow this process you can basically with a few commands deploy to a subdomain that anyone can access so I did that for our example so this is a wood so
here we have a similar implementation oh wow wow okay so get out no I'm
getting so what we're gonna do is static no what do you call that shit copy so I'm gonna copy and paste that bookmark that I generated thanks to that wonderful utility and let's see how I am adding a bookmark all right so
if oh you're gonna notice well here's all garbled but in my connect connect where is it there guys done I'm still here I'm kidding so when I'm
calling connect I'm actually calling jitsu see so that's what's gonna allow us to bring it to NDC was it NDC also calm yeah so
So, oh that didn't work. Let me correct the bookmark. I think Chrome is gonna be, yeah. Thanks Chrome. Oh wow. Oh okay so here I am. I'm gonna fire this. Oh so we have
a few zombie guys. So if you guys have an iPhone you can also go to
iphone.html. Oh the scrolling is actually not synchronized so that will make people tomb. So alright so this really silly demo actually shows you all the entirety of the Socket.IO API even though for the new website and
I'm gonna quickly go over the new stuff that we have just to close. Oh by the way thanks Eric. Eric is from Sweden. He created the The Asteroids game so he did the bulk of the work. I simply tied Socket.IO into it. Thanks
Kenneth Belkovski. He's Norwegian and a placeholder. So quickly what's next for Socket.IO and we're probably releasing 1.0 the next week. We're including the new core of functionality called engine.io which is
the last thing I'm working on is the cluster integration so that it's gonna use all the processes in your machine. Right now you have node.js and the name is really appropriate because you only have one node but we're gonna make it so that you drop Socket.IO it's gonna use all your cores
you're not even gonna notice. It's gonna be so fast. I should have a wow slide here. So we're gonna have cdn.socket.io provided by nodejitsu so you're no longer gonna have to host it yourself or do slash socket.io slash socket.io.js. You're just gonna do cdn.socket.io slash socket.io.js or the version or something and finally we're having a
new website and the new logo which you saw as the first slide which I'm really excited about. I don't like the current website at all so new logo that's it I picked this color so that you remember it well and this one and
this one. So any questions? Say again. Oh peer-to-peer I hope so. So as I was
writing this example I was thinking it would be really interesting if Socket.IO could also expose some sort of like peer-to-peer API even though it's not so in the future if we do get a peer-to-peer API we can make that more seamless but sometimes with certain security considerations it would be really useful to be aware of other
sockets out there and be able to just send the messages transparently and not have the server be a broker. Yep. Any other question? No. No questions. So thank you and sorry for the extended time.