Pressemitteilung SEC warnt Investoren über binäre Optionen und Gebühren Zypern-basierte Unternehmen mit dem Verkauf von ihnen illegal in den USA FÜR IMMEDIATE RELEASE 2013-103 Washington, DC 6. Juni 2013 mdash Die Securities and Exchange Commission warnte heute Investoren über die potenziellen Risiken der Investition in binäre Optionen und hat ein in Zypern gegründetes Unternehmen beauftragt, sie illegal an US-Investoren zu verkaufen. Bei den binären Optionen handelt es sich um Wertpapiere in Form von Optionskontrakten, deren Auszahlung davon abhängt, ob der zugrunde liegende Vermögenswert - zum Beispiel eine Aktien des Unternehmens - steigt oder sinkt. In solch einer all-oder nichts Auszahlungsstruktur, Investoren Wetten auf eine Aktienkurserhöhung Gesicht zwei mögliche Ergebnisse, wenn der Vertrag abläuft: Sie erhalten entweder eine vorgegebene Menge an Geld, wenn der Wert des Vermögenswertes über den festen Zeitraum erhöht oder nein Geld überhaupt, wenn es sank. Die SEC behauptet, dass Banc de Binary Ltd. Binäroptionen an Investoren in den USA angeboten und verkauft hat, ohne die Wertpapiere, wie sie im Rahmen der Bundesgesetzgebung vorgeschrieben sind, zu registrieren. Das Unternehmen hat weitgehend U. S-Kunden durch Werbung über YouTube-Videos, Spam-E-Mails und andere Internet-basierte Werbung angefordert. Banc de Binary Vertreter haben mit Investoren direkt per Telefon, E-Mail und Instant Messenger Chats kommuniziert. Banc de Binary hat auch als Broker beim Angebot und Verkauf dieser Wertpapiere gehandelt, aber nicht mit der SEC als Makler registriert, wie es im US-amerikanischen Gesetz vorgeschrieben ist. Die SEC und die Commodity Futures Trading Commission (CFTC) haben heute einen gemeinsamen Investor Alert veröffentlicht, um Investoren über betrügerische Promotion-Systeme mit binären Optionen und binären Optionen Trading-Plattformen zu warnen. Ein Großteil des Binäroptionsmarktes betreibt über internetbasierte Handelsplattformen, die nicht zwangsläufig den anwendbaren US-amerikanischen Regulierungsanforderungen entsprechen und illegale Aktivitäten ausüben können. Gerade weil ausländische Unternehmen leichter mit amerikanischen Investoren kommunizieren können, bedeutet das nicht, dass sie unsere langjährigen Gesetze, die die Anleger schützen, durch die Registrierung von Wertpapieren beschützen sollten, sagte Andrew J. Ceresney, Co-Direktor der SECs Division of Enforcement. Banc de Binary kontaktierte U. S. Investoren über das Internet und YouTube aber völlig ignoriert die US-Wertpapiergesetze Registrierung Anforderungen. Wir werden dieses Verhalten konsequent bekämpfen, egal woher es kommt. Nach der Beschwerde der SEC gegen Banc de Binary, die im Bundesgericht in Nevada eingereicht wurde, begann das Unternehmen, Binäroptionen an US-Investoren im Jahr 2010 anzubieten und zu verkaufen. Banc de Binary veranlasste Investoren, Konten mit der Firma zu erstellen, Geld in diese Konten einzahlen und dann Kauf von binären Optionen, deren zugrunde liegende Vermögenswerte Aktien - und Aktienindizes enthalten. Banc de Binarys Aufforderung von U. S. Investoren war sehr erfolgreich und zog einige Kunden mit sehr bescheidenen Mitteln an. Zum Beispiel hatte ein Investor ein monatliches Einkommen von 300 und einen Nettovermögen von weniger als 25.000, und ein anderer Kunde wurde ermutigt, zusätzliche Mittel in sein Banc de Binary Handelskonto einzahlen, auch nachdem er den Banc de Binary-Vertreter mitgeteilt hatte, dass er arbeitslos war Weniger als 1.000 in seinem Girokonto. Die SEC-Beschwerde sucht Ablehnung plus Vorurteil Zinsen, finanzielle Sanktionen und vorläufige und dauerhafte Unterlassungsansprüche gegen Banc de Binary unter anderem Erleichterung. Die CFTC hat heute eine Parallelaktion gegen Banc de Binary angekündigt. Die SEC-Untersuchung wurde von Leslie A. Hakala und C. Dabney ORiordan des Los Angeles Regional Office durchgeführt. Die SECs werden von John W. Berry und Frau Hakala geführt. Die SEC schätzt die Unterstützung der CFTC in dieser Angelegenheit. Der Investor Alert auf binäre Optionen wurde gemeinsam von der SECs Office of Investor Education und Advocacy und der CFTCs Office of Consumer Outreach ausgestellt. Das Bulletin erörtert im Detail die potenziellen Risiken der Investition in binäre Optionen und warnt Investoren, dass sie nicht die volle Sicherung der föderalen Wertpapiere und Rohstoffgesetze haben, wenn sie unregistrierte binäre Optionen kaufen, die nicht der Aufsicht der US-Regulierungsbehörden unterliegen. Anleger sollten sich bewusst sein, das Potenzial für Betrug in diesem Bereich sowie der Realität, dass sie ihre gesamte Investition verlieren können, sagte Lori Schock, Direktor der SECs Office of Investor Education und Advocacy. Wir ermutigen die Anleger, den Hintergrund von Brokern und Beratern und Handelsplattformen zu überprüfen, bevor sie eine Investitionsentscheidung treffen. Wenn die Anleger keine einfachen Hintergrundinformationen erhalten können, z. B. ob der Finanzfachmann bei der SEC oder der FINRA registriert ist, dann sollten sie äußerst vorsichtig sein. Verwandte MaterialienKapitel 17. WebSocket WebSocket ermöglicht bidirektionales, nachrichtenorientiertes Streaming von Text - und Binärdaten zwischen Client und Server. Es ist die nächstgelegene API zu einer Rohnetzsteckdose im Browser. Außer einer WebSocket-Verbindung ist auch viel mehr als ein Netzwerk-Socket, da der Browser alle Komplexität hinter einer einfachen API abstrakt und eine Reihe von zusätzlichen Diensten bietet: Verbindungsverhandlung und gleiche Herkunftspolitik Durchsetzung Interoperabilität mit vorhandener HTTP-Infrastruktur Meldungsorientierte Kommunikation und Effiziente Message Framing Subprotocol Verhandlung und Erweiterbarkeit WebSocket ist einer der vielseitigsten und flexibelsten Transporte im Browser. Die einfache und minimale API ermöglicht es uns, beliebige Anwendungsprotokolle zwischen Client und Serveranything von einfachen JSON-Payloads zu benutzerdefinierten Binär-Message-Formaten in einer Streaming-Mode zu platzieren und zu liefern, wobei jede Seite jederzeit Daten senden kann. Allerdings ist der Kompromiss mit benutzerdefinierten Protokollen, dass sie, gut, benutzerdefinierte sind. Die Anwendung muss für fehlende Zustandsverwaltung, Komprimierung, Zwischenspeicherung und andere Dienste, die sonst vom Browser bereitgestellt wird, berücksichtigen. Es gibt immer Design-Einschränkungen und Performance-Kompromisse, und die Nutzung von WebSocket ist keine Ausnahme. Kurz gesagt, WebSocket ist kein Ersatz für HTTP, XHR oder SSE, und für die beste Leistung ist es entscheidend, dass wir die Stärken jedes Transports nutzen. WebSocket ist ein Satz von mehreren Standards: Die WebSocket API wird durch das W3C definiert und das WebSocket-Protokoll (RFC 6455) und seine Erweiterungen werden von der HyBi Working Group (IETF) definiert. WebSocket API Die vom Browser bereitgestellte WebSocket API ist bemerkenswert klein und einfach. Wieder einmal werden alle Low-Level-Details des Verbindungsmanagements und der Nachrichtenverarbeitung vom Browser übernommen. Um eine neue Verbindung zu initiieren, benötigen wir die URL einer WebSocket-Ressource und ein paar Anwendungs-Callbacks: Sende den Blob-Inhalt als binäre Payload Die WebSocket-API akzeptiert ein DOMString-Objekt, das als UTF-8 auf dem Draht oder einem von ArrayBuffer codiert ist , ArrayBufferView oder Blob-Objekte für binäre Transfers. Beachten Sie jedoch, dass die letztgenannten Binäroptionen einfach eine API-Bequemlichkeit sind: Auf dem Draht wird ein WebSocket-Frame entweder als Binär oder Text über ein einziges Bit markiert. Wenn also die Anwendung oder der Server andere Content-Type-Informationen über die Payload benötigen, dann müssen sie einen zusätzlichen Mechanismus verwenden, um diese Daten zu kommunizieren. Die send () - Methode ist asynchron: die bereitgestellten Daten werden vom Client in die Warteschlange gestellt und die Funktion wird sofort zurückgegeben. Als Ergebnis, vor allem bei der Übertragung von großen Nutzlasten, nicht die schnelle Rückkehr für ein Signal, dass die Daten gesendet wurde Um zu vermeiden, die Menge an Daten in der Warteschlange durch den Browser, kann die Anwendung das gepufferteAmount-Attribut auf dem Socket abfragen: Senden Sie die nächste Aktualisieren, wenn der Puffer leer ist Das vorhergehende Beispiel versucht, Anwendungsaktualisierungen an den Server zu senden, aber nur, wenn die vorherigen Nachrichten vom Client-Puffer abgeleitet wurden. Warum mit solchen Kontrollen belasten Alle WebSocket-Nachrichten werden in der exakten Reihenfolge ausgeliefert, in der sie vom Kunden in die Warteschlange gestellt werden. Infolgedessen verzögert ein großer Rückstand von Warteschlangennachrichten oder sogar eine einzige große Nachricht die Zustellung von Nachrichten, die hinter der Kopfzeile blockiert werden. Um dieses Problem zu umgehen, kann die Anwendung große Nachrichten in kleinere Stücke aufteilen, den gepuffertenAmount überwachen Wert sorgfältig zu vermeiden Kopf-of-line-Blockierung, und sogar implementieren ihre eigene Priorität Warteschlange für anstehende Nachrichten anstatt blind wartig sie alle auf der Steckdose. Viele Anwendungen generieren mehrere Klassen von Nachrichten: hochprioritäre Updates wie Steuerungsverkehr und Updates mit niedriger Priorität wie Hintergrundübertragungen. Um die Zustellung zu optimieren, sollte die Anwendung genau darauf achten, wie und wann jede Art von Nachricht in der Warteschlange in der Socket steht. Subprotokoll Negotiation WebSocket-Protokoll macht keine Annahmen über das Format jeder Nachricht: Ein einziges Bit verfolgt, ob die Nachricht Text - oder Binärdaten enthält, So dass es vom Client und Server effizient decodiert werden kann, aber ansonsten sind die Nachrichteninhalte undurchsichtig. Im Gegensatz zu HTTP - oder XHR-Anforderungen, die zusätzliche Metadaten über HTTP-Header jeder Anforderung und Antwort vermitteln, gibt es keinen solchen gleichwertigen Mechanismus für eine WebSocket-Nachricht. Wenn also zusätzliche Metadaten über die Nachricht benötigt werden, müssen sich der Client und der Server verpflichten, ein eigenes Subprotokoll zu implementieren, um diese Daten zu kommunizieren: Der Client und der Server können sich auf ein festes Nachrichtenformat upfronte. g vereinbaren. Die gesamte Kommunikation erfolgt über JSON-codierte Nachrichten oder ein benutzerdefiniertes Binärformat, und notwendige Nachrichtenmetadaten werden Teil der codierten Struktur sein. Wenn der Client und der Server unterschiedliche Datentypen übertragen müssen, können sie sich auf einen konsistenten Nachrichtenkopf verständigen, der verwendet werden kann, um die Anweisungen zu kommunizieren, um den Rest der Nutzlast zu dekodieren. Eine Mischung aus Text - und Binärnachrichten kann verwendet werden, um die Nutzdaten und Metadateninformationen zu vermitteln. Eine Textnachricht kann ein Äquivalent von HTTP-Headern vermitteln, gefolgt von einer Binärnachricht mit der Anwendungs-Payload. Diese Liste ist nur eine kleine Auswahl möglicher Strategien. Die Flexibilität und der geringe Overhead einer WebSocket-Nachricht kommen auf Kosten der zusätzlichen Anwendungslogik. Allerdings sind die Nachrichten-Serialisierung und das Management von Metadaten nur ein Teil des Problems. Sobald wir das Serialisierungsformat für unsere Nachrichten festlegen, wie stellen wir sicher, dass sowohl Client als auch Server einander verstehen und wie halten wir sie synchron. Zum Glück bietet WebSocket eine Einfache und bequeme Unterprotokoll-Verhandlungs-API, um das zweite Problem zu lösen. Der Client kann werben, welche Protokolle er auf dem Server als Teil seines anfänglichen Verbindungshändedrucks unterstützt: Array von Unterprotokollen, um während des WebSocket-Handshakes zu werben Überprüfen Sie das vom Server gewählte Unterprotokoll Wie das vorstehende Beispiel veranschaulicht, akzeptiert der WebSocket-Konstruktor ein optionales Array von Unterprotokollnamen , Die es dem Kunden ermöglicht, die Liste der Protokolle, die er versteht oder bereit ist, für diese Verbindung zu verwenden, zu werben. Die angegebene Liste wird an den Server gesendet und der Server darf eines der vom Client angekündigten Protokolle auswählen. Wenn die Unterprotokollverhandlung erfolgreich ist, wird der Onopen-Rückruf auf dem Client abgefeuert, und die Anwendung kann das Protokollattribut auf dem WebSocket-Objekt abfragen, um das gewählte Protokoll zu ermitteln. Auf der anderen Seite, wenn der Server keine der vom Client angekündigten Clientprotokolle unterstützt, ist der WebSocket-Handshake unvollständig: Der Onerror-Rückruf wird aufgerufen und die Verbindung wird beendet. Die Unterprotokollnamen werden von der Anwendung definiert und werden während des ersten HTTP-Handshakes an den Server gesendet. Andererseits hat das angegebene Subprotokoll keine Auswirkung auf die Kern-WebSocket-API. WebSocket-Protokoll Das von der HyBi-Arbeitsgruppe entwickelte WebSocket-Drahtprotokoll (RFC 6455) besteht aus zwei hochrangigen Komponenten: dem HTTP-Handshake, mit dem die Parameter der Verbindung verhandelt werden, und ein binärer Nachrichtenrahmen, um niedrige Overhead - Basierte Bereitstellung von Text - und Binärdaten. Das WebSocket-Protokoll versucht, die Ziele der vorhandenen bidirektionalen HTTP-Technologien im Kontext der vorhandenen HTTP-Infrastruktur als solche zu adressieren, es ist entworfen, um über HTTP-Ports zu arbeiten 80 und 443 Allerdings beschränkt das Design WebSocket nicht auf HTTP und zukünftige Implementierungen könnte Verwenden Sie einen einfacheren Handshake über einen dedizierten Port, ohne das gesamte Protokoll neu zu erfinden. - WebSocket-Protokoll RFC 6455 WebSocket-Protokoll ist ein voll funktionsfähiges, eigenständiges Protokoll, das außerhalb des Browsers verwendet werden kann. Allerdings ist seine primäre Anwendung als bidirektionaler Transport für Browser-basierte Anwendungen. Binary Framing Layer Client und Server WebSocket Applikationen kommunizieren über eine nachrichtsorientierte API: Der Absender stellt eine beliebige UTF-8 oder binäre Nutzlast zur Verfügung und der Empfänger wird über die Zustellung informiert, wenn die gesamte Nachricht verfügbar ist. Um dies zu aktivieren, verwendet WebSocket ein benutzerdefiniertes Binär-Framing-Format (Abbildung 17-1), das jede Applikationsnachricht in einen oder mehrere Frames aufteilt. Transportiert sie zum Ziel, setzt sie wieder zusammen und benachrichtigt den Empfänger, sobald die gesamte Nachricht empfangen wurde. Abbildung 17-1. WebSocket-Frame: 214 Bytes Nutzlast Frame Die kleinste Kommunikationseinheit, die jeweils einen Frame-Header mit variabler Länge und eine Nutzlast enthält, die die Applikationsnachricht ganz oder teilweise tragen kann. Nachricht Eine vollständige Sequenz von Frames, die einer logischen Applikationsnachricht zuordnen. Die Entscheidung, eine Anwendungsnachricht in mehrere Frames zu zerlegen, wird durch die zugrunde liegende Implementierung des Client - und Server-Framing-Codes gemacht. Daher bleiben die Applikationen immer wieder von den einzelnen WebSocket-Frames nicht bewusst oder wie das Framing durchgeführt wird. Allerdings ist es noch sinnvoll, die Highlights zu verstehen, wie jeder WebSocket-Frame auf dem Draht dargestellt wird: Das erste Bit jedes Frames (FIN) gibt an, ob der Frame ein endgültiges Fragment einer Nachricht ist. Eine Nachricht kann aus nur einem einzigen Rahmen bestehen. Der Opcode (4 Bits) gibt den Typ des übertragenen Frames an: Text (1) oder Binär (2) zum Übertragen von Applikationsdaten oder eines Steuerrahmens wie Anschlussschluss (8), Ping (9) und Pong (10) für Anschlusslifigkeit Prüfungen Das Maskenbit zeigt an, ob die Nutzlast maskiert ist (für Nachrichten, die vom Client an den Server gesendet werden). Die Nutzlast wird als Feld mit variabler Länge dargestellt: Wenn 0125, dann ist das die Nutzlastlänge. Wenn 126, dann stellen die folgenden 2 Bytes eine 16-Bit-Ganzzahl ohne Vorzeichen dar, die die Rahmenlänge angibt. Wenn 127, dann stellen die folgenden 8 Bytes eine 64-Bit-Ganzzahl ohne Vorzeichen dar, die die Rahmenlänge angibt. Der Maskierungsschlüssel enthält einen 32-Bit-Wert, der verwendet wird, um die Nutzlast zu maskieren. Payload enthält die Anwendungsdaten und benutzerdefinierte Erweiterungsdaten, wenn der Client und der Server eine Erweiterung ausgehandelt haben, wenn die Verbindung hergestellt wurde. Die Nutzlast aller Client-initiierten Frames wird mit dem im Frame-Header angegebenen Wert maskiert: Dadurch wird verhindert, dass bösartige Scripts, die auf dem Client ausgeführt werden, einen Cache-Poisoning-Angriff gegen Intermediäre ausführen, die das WebSocket-Protokoll nicht verstehen können. Für ausführliche Details dieses Angriffs, beziehen Sie sich auf Sprechen mit sich selbst für Spaß und Prot. Präsentiert auf der W2SP 2011. Als Ergebnis erhält jeder Server-gesendete WebSocket-Frame 210 Bytes Framing Overhead. Der Client muss auch einen Maskierungsschlüssel senden, der dem Header zusätzliche 4 Bytes hinzufügt, was zu 614 Bytes über Overhead führt. Es sind keine anderen Metadaten wie Header-Felder oder andere Informationen über die Nutzdaten verfügbar: Alle WebSocket-Kommunikation wird durch den Austausch von Frames durchgeführt, die die Nutzlast als opake Blob von Anwendungsdaten behandeln. WebSocket Multiplexing und Head-of-Line-Blocking WebSocket ist anfällig für Head-of-Line-Blocking: Nachrichten können in einen oder mehrere Frames aufgeteilt werden, aber Frames aus verschiedenen Nachrichten können nicht verschachtelt werden, da es kein Äquivalent zu einer Stream-ID gibt Der HTTP2-Framing-Mechanismus siehe Streams, Messages und Frames). Infolgedessen wird eine große Nachricht, auch wenn sie in mehrere WebSocket-Frames aufgeteilt ist, die Lieferung von Frames blockieren, die mit anderen Nachrichten verknüpft sind. Wenn Ihre Anwendung latenzempfindliche Daten liefert, achten Sie auf die Nutzdatengröße jeder Nachricht und erwägen Sie, große Nachrichten in mehrere Anwendungsnachrichten zu teilen. Der Mangel an Multiplexing in der Kern-WebSocket-Spezifikation bedeutet auch, dass jede WebSocket-Verbindung eine dedizierte TCP-Verbindung erfordert, die möglicherweise Ein potenzielles Problem für HTTP1.x-Implementierungen aufgrund einer eingeschränkten Anzahl von Verbindungen pro Ursprung, die vom Browser verwaltet werden, finden Sie unter Abbau von Client - und Serverressourcen. Auf der hellen Seite adressiert die von der HyBi-Arbeitsgruppe entwickelte Multiplexing-Erweiterung für WebSockets die letztere Einschränkung: Mit dieser Erweiterung kann eine TCP-Verbindung mehrere virtuelle WebSocket-Verbindungen bereitstellen, indem sie mit einer Kanal-ID markierte Frames verkapseln. Die Multiplex-Erweiterung verwaltet separate logische Kanäle , Von denen jeder das logische Äquivalent einer unabhängigen WebSocket-Verbindung, einschließlich separater Handshake-Header, vollständig bereitstellt. - WebSocket Multiplexing (Draft 10) Mit dieser Erweiterung können mehrere WebSocket-Verbindungen (Kanäle) über dieselbe TCP-Verbindung gemultiplext werden. Jedoch ist jeder einzelne Kanal immer noch anfällig für Head-of-Line-Blocking. Daher ist ein potentieller Workaround die Verwendung unterschiedlicher Kanäle oder dedizierter TCP-Verbindungen, um mehrere Meldungen parallel zu multiplexen. Schließlich ist zu beachten, dass die vorherige Erweiterung nur für HTTP1.x-Verbindungen erforderlich ist. Obwohl keine offizielle Spezifikation für den Transport von WebSocket-Frames mit HTTP2 verfügbar ist, wäre dies viel einfacher: HTTP2 hat ein eingebautes Stream-Multiplexing und mehrere WebSocket-Verbindungen können innerhalb einer einzigen Session transportiert werden, indem sie WebSocket-Frames innerhalb des HTTP2-Framing-Mechanismus einkapseln. Protokoll-Erweiterungen Die WebSocket-Spezifikation ermöglicht Protokoll-Erweiterungen: Das Drahtformat und die Semantik des WebSocket-Protokolls können mit neuen Opcodes und Datenfeldern erweitert werden. Während es etwas ungewöhnlich ist, ist dies ein sehr leistungsfähiges Feature, da es dem Client und dem Server ermöglicht, zusätzliche Funktionalität auf der Basis-WebSocket-Framing-Schicht zu implementieren, ohne dass ein Eingriff oder eine Kooperation aus dem Anwendungscode erforderlich ist. Was sind einige Beispiele für WebSocket-Protokoll-Erweiterungen Die HyBi-Arbeitsgruppe, die für die Entwicklung der WebSocket-Spezifikation verantwortlich ist, listet zwei offizielle Erweiterungen in der Entwicklung auf: Eine Multiplex-Erweiterung für WebSockets Diese Erweiterung bietet eine Möglichkeit für separate logische WebSocket-Verbindungen, einen Basiswert zu teilen Transportverbindung. Komprimierungserweiterungen für WebSocket Ein Framework zum Erstellen von WebSocket-Erweiterungen, die dem WebSocket-Protokoll Komprimierungsfunktionalität hinzufügen. Wie bereits erwähnt, benötigt jede WebSocket-Verbindung eine dedizierte TCP-Verbindung, die ineffizient ist. Multiplexing-Erweiterung dieses Problem durch die Erweiterung jedes WebSocket-Frames mit einer zusätzlichen Kanal-ID, damit mehrere virtuelle WebSocket-Kanäle eine einzelne TCP-Verbindung zu teilen. Ebenso stellt die Basis-WebSocket-Spezifikation keinen Mechanismus oder Bestimmungen für die Komprimierung der übertragenen Daten bereit: Jeder Rahmen trägt Nutzdaten, wie sie von der Anwendung bereitgestellt werden. Infolgedessen, während dies möglicherweise kein Problem für optimierte binäre Datenstrukturen ist, kann dies zu einem hohen Byteübertragungsaufwand führen, es sei denn, die Anwendung implementiert eine eigene Datenkomprimierungs - und Dekompressionslogik. In Wirklichkeit ermöglicht die Komprimierungserweiterung ein Äquivalent von Transfer-Codierungsverhandlungen, die von HTTP bereitgestellt werden. Um eine oder mehrere Erweiterungen zu aktivieren, muss der Client sie im anfänglichen Upgrade-Handshake werben und der Server muss die Erweiterungen auswählen und quittieren, die für die Lebensdauer der ausgehandelten Verbindung verwendet werden. Für ein Hands-on-Beispiel können Sie sich die Upgrade-Sequenz genauer ansehen. WebSocket Multiplexing und Komprimierung in der Wildnis Seit Mitte 2013 wird das WebSocket-Multiplexing noch nicht von einem beliebigen Browser unterstützt. Ebenso gibt es nur begrenzte Unterstützung für die Komprimierung: Google Chrome und die neuesten WebKit-Browser können eine x-webkit-deflate-frame-Erweiterung auf den Server werben. Der deflate-frame basiert jedoch auf einer veralteten Revision des Standards und wird in Zukunft veraltet sein. Wie der Name schon sagt, komprimiert per-frame die Payload-Inhalte auf einer Frame-by-Frame-Basis, die für große Nachrichten suboptimal ist, die zwischen mehreren Frames aufgeteilt werden können. Infolgedessen haben die letzten Revisionen der Komprimierungserweiterung auf die Nachrichten-Kompression umgestellt, was die gute Nachricht gibt. Die schlechte Nachricht ist per-Message-Komprimierung ist noch experimentell und ist noch nicht in jedem beliebigen Browser verfügbar. Infolgedessen sollte die Anwendung den Inhaltstyp der übertragenen Daten genau beachten und gegebenenfalls eine eigene Komprimierung anwenden. Das heißt, zumindest bis native WebSocket Kompression Unterstützung ist weit über alle beliebten Browser verfügbar. Dies ist besonders wichtig für mobile Anwendungen, bei denen jedes unnötige Byte dem Anwender hohe Kosten bringt. HTTP-Upgrade-Verhandlung Das WebSocket-Protokoll bietet viele leistungsstarke Funktionen: Nachrichten-orientierte Kommunikation, eigene Binär-Framing-Layer, Subprotocol-Verhandlung, optionale Protokoll-Erweiterungen und vieles mehr. Als Ergebnis, bevor irgendwelche Nachrichten ausgetauscht werden können, müssen der Client und der Server die entsprechenden Parameter vermitteln, um die Verbindung herzustellen. Die Nutzung von HTTP zur Durchführung des Handshakes bietet mehrere Vorteile. Zuerst macht es WebSockets kompatibel mit vorhandener HTTP-Infrastruktur: WebSocket-Server können auf Port 80 und 443 laufen, die häufig die einzigen offenen Ports für den Client sind. Zweitens erlaubt es uns, den HTTP-Upgrade-Fluss mit benutzerdefinierten WebSocket-Headern wiederzuverwenden und zu erweitern, um die Verhandlung durchzuführen: Sec-WebSocket-Version Vom Client gesendet, um die Version (13 für RFC6455) des WebSocket-Protokolls anzugeben, das es verwenden möchte. Wenn der Server die Client-Version nicht unterstützt, muss er mit einer Liste unterstützter Versionen antworten. Sec-WebSocket-Key Ein vom Autor gesendeter, vom Autor gestellter Schlüssel, der als Herausforderung für den Server dient, um zu beweisen, dass der Server die angeforderte Version des Protokolls unterstützt. Sec-WebSocket-Accept Server-Antwort, die den signierten Wert von Sec-WebSocket-Key enthält, was beweist, dass sie die angeforderte Protokollversion versteht. Sec-WebSocket-Protokoll Zur Verhandlung der Applikation subprotocol: Client kündigt die Liste der unterstützten Protokolle an, die der Server mit einem einzigen Protokollnamen antworten muss. Sec-WebSocket-Erweiterungen Verwendet, um WebSocket-Erweiterungen zu verhandeln, die für diese Verbindung verwendet werden sollen: Client bewirbt unterstützte Erweiterungen und der Server bestätigt eine oder mehrere Erweiterungen, indem er denselben Header zurückgibt. Damit haben wir jetzt alle notwendigen Stücke, um ein HTTP-Upgrade durchzuführen und eine neue WebSocket-Verbindung zwischen dem Client und dem Server zu verhandeln: Alle RFC6455-kompatiblen WebSocket-Server verwenden den gleichen Algorithmus, um die Antwort auf die Client-Herausforderung zu berechnen: den Inhalt der Sec-WebSocket-Key ist mit einer eindeutigen GUID-Zeichenfolge verknüpft, die im Standard definiert ist, ein SHA1-Hash wird berechnet und die resultierende Zeichenfolge wird base-64 codiert und an den Client zurückgesendet. Mindestens muss ein erfolgreicher WebSocket-Handshake die Protokollversion und einen vom Benutzer erstellten automatisch generierten Challenge-Wert enthalten, gefolgt von einem 101 HTTP-Antwortcode (Switching Protocols) vom Server mit einer Hash-Challenge-Antwort, um das ausgewählte Protokoll zu bestätigen Version: Client muss Sec-WebSocket-Version und Sec-WebSocket-Key senden. Server muss das Protokoll durch die Rücksendung von Sec-WebSocket-Accept bestätigen. Der Kunde kann eine Liste der Antragsunterprotokolle über Sec-WebSocket-Protokoll senden. Server muss eines der beworbenen Unterprotokolle auswählen und über Sec-WebSocket-Protokoll zurückgeben. Wenn der Server keine davon unterstützt, wird die Verbindung abgebrochen. Client kann eine Liste von Protokollerweiterungen in Sec-WebSocket-Erweiterungen senden. Server kann eine oder mehrere ausgewählte Erweiterungen über Sec-WebSocket-Erweiterungen bestätigen. Wenn keine Erweiterungen vorhanden sind, geht die Verbindung ohne sie aus. Schließlich, sobald der vorhergehende Handshake abgeschlossen ist und wenn der Handshake erfolgreich ist, kann die Verbindung nun als Zwei-Wege-Kommunikationskanal für den Austausch von WebSocket-Nachrichten verwendet werden. Von hier aus gibt es keine andere explizite HTTP-Kommunikation zwischen dem Client und dem Server und das WebSocket-Protokoll übernimmt. Proxies, Intermediaries und WebSockets In der Praxis haben viele Benutzer aus Sicherheits - und politischen Gründen einen eingeschränkten Satz von offenen Portsspezifisch Port 80 (HTTP) und Port 443 (HTTPS). Als Ergebnis wird die WebSocket-Verhandlung über den HTTP-Upgrade-Ablauf durchgeführt, um die beste Kompatibilität mit bestehenden Netzwerkrichtlinien und Infrastrukturen zu gewährleisten. Allerdings, wie wir bereits in Proxies, Intermediaries, TLS und New Protocols im Web festgestellt haben. Viele bestehende HTTP-Intermediäre können das neue WebSocket-Protokoll nicht verstehen, was zu einer Vielzahl von Fehlerfällen führen kann: Blindverbindungs-Upgrades, unbeabsichtigte Pufferung von WebSocket-Frames, Content-Modifikation ohne Verständnis des Protokolls, Fehlklassifizierung von WebSocket-Datenverkehr als kompromittierte HTTP-Verbindungen und bald. Der WebSocket Key und Accept Handshake adressiert einige dieser Probleme: Es ist eine Sicherheitsrichtlinie gegen Server und Intermediäre, die die Verbindung blind aktualisieren können, ohne das WebSocket-Protokoll zu verstehen. Allerdings, während diese Vorsichtsmaßnahme einige Deployment-Probleme mit expliziten Proxies, ist es dennoch unzureichend für transparente Proxies, die analysieren und ändern können die Daten auf dem Draht ohne vorherige Ankündigung. Der Workaround Stellen Sie eine sichere End-to-End-Tunneli. e her. Verwenden Sie WSS Durch das Verhandeln einer TLS-Sitzung vor dem Ausführen des HTTP-Upgrade-Handshakes, stellen der Client und der Server einen verschlüsselten Tunnel her, der alle zuvor aufgeführten Bedenken auflöst. Dies gilt insbesondere für mobile Clients, deren Verkehr oft eine Vielzahl von Proxy-Diensten durchläuft, die mit WebSocket nicht gut spielen können. WebSocket Use Cases und Performance WebSocket API bietet eine einfache Schnittstelle für bidirektionales, nachrichtenorientiertes Streaming von Text - und Binärdaten zwischen Client und Server: Übergeben Sie eine WebSocket-URL an den Konstruktor, richten Sie einige JavaScript-Callback-Funktionen ein, und wir sind auf und Runningthe Rest wird vom Browser gehandhabt. Fügen Sie hinzu, dass das WebSocket-Protokoll, das Binär-Framing, Erweiterbarkeit und Subprotocol-Verhandlung bietet, und WebSocket wird eine perfekte Passform für die Bereitstellung von benutzerdefinierten Anwendungsprotokollen im Browser. Jedoch, genau wie bei jeder Diskussion über die Leistung, während die Implementierungskomplexität des WebSocket-Protokolls von der Anwendung verborgen ist, hat es dennoch wichtige Leistungsimplikationen für wie und wann WebSocket verwendet werden sollte. WebSocket ist kein Ersatz für XHR oder SSE, und für die beste Leistung ist es entscheidend, dass wir die Stärken eines jeden Transports nutzen. Siehe XHR Use Cases und Performance und SSE Use Cases und Performance für eine Überprüfung der Leistungsmerkmale jedes Transports. Request and Response Streaming WebSocket ist der einzige Transport, der eine bidirektionale Kommunikation über dieselbe TCP-Verbindung ermöglicht (Abbildung 17-2): Der Client und der Server können nach Belieben Nachrichten ausrichten. Als Ergebnis bietet WebSocket eine geringe Latenzzeit von Text - und Binäranwendungsdaten in beide Richtungen. Abbildung 17-2. Der Kommunikationsfluss von XHR, SSE und WebSocket XHR ist für die Transaktionsanforderung-Antwort-Kommunikation optimiert: Der Client sendet die volle, gut geformte HTTP-Anforderung an den Server und der Server antwortet mit einer vollständigen Antwort. Es gibt keine Unterstützung für Anforderungs-Streaming, und bis die Streams-API verfügbar ist, keine zuverlässige Cross-Browser-Antwort-Streaming-API. SSE ermöglicht eine effiziente, servergesteuerte Server-to-Client-Streaming von textbasierten Daten: Der Client leitet die SSE-Verbindung ein und der Server nutzt das Ereignisquellenprotokoll zum Streamen von Updates für den Client. Der Kunde kann nach dem ersten Handshake keine Daten an den Server senden. Ausbreitung und Queuing Latency Switching Transporte von XHR zu SSE oder WebSocket verringert nicht den Roundtrip zwischen Client und Server Unabhängig vom Transport ist die Ausbreitungslatenz der Datenpakete gleich. Abgesehen von der Ausbreitungslatenz gibt es aber auch die Warteschlangen-Latenz. Die Zeit, die die Nachricht auf den Client oder Server warten muss, bevor sie an die andere Partei weitergeleitet werden kann. Im Fall der XHR-Abfrage ist die Warteschlangen-Latenzzeit eine Funktion des Client-Abfrageintervalls: Die Nachricht kann auf dem Server verfügbar sein, aber sie kann nicht gesendet werden, bis die nächste Client-XHR-Anfrage die Modellierungsleistung von XHR Polling enthält. Im Gegensatz dazu verwenden sowohl SSE als auch WebSocket eine persistente Verbindung, die es dem Server ermöglicht, die Nachricht (und den Client im Falle von WebSocket), sobald er verfügbar ist, zu versenden. Infolgedessen bezieht sich die Low-Latency-Lieferung für SSE und WebSocket speziell auf die Beseitigung der Nachrichtenwarteschlangen-Latenz. Wir haben noch nicht herausgefunden, wie man WebSocket-Datenpakete schneller als die Lichtgeschwindigkeit umsetzt. Message Overhead Sobald eine WebSocket-Verbindung aufgebaut ist, tauschen der Client und der Server Daten über das WebSocket-Protokoll aus: Anwendungsnachrichten werden in einen oder mehrere Frames aufgeteilt Von denen fügt von 2 bis 14 Bytes Overhead. Da das Framing über ein benutzerdefiniertes Binärformat erfolgt, können sowohl UTF-8 als auch binäre Anwendungsdaten effizient über denselben Mechanismus codiert werden. Wie verhält sich der Vergleich mit XHR und SSE SSE fügt bis zu 5 Bytes pro Nachricht hinzu, ist aber auf UTF-8 Inhalt beschränkt, siehe nur Event Stream Protocol. HTTP1.x-Anfragen (XHR oder anderweitig) werden zusätzliche 500800 Bytes HTTP-Metadaten und Cookies zum Messen und Steuern von Protokoll Overhead übertragen. HTTP2 komprimiert die HTTP-Metadaten, was den Overhead erheblich reduziert, siehe Header Compression. In der Tat, wenn die Header nicht zwischen Anfragen ändern, kann der Overhead so niedrig wie 8 Bytes Beachten Sie, dass diese Overhead-Nummern nicht die Overhead von IP, TCP und TLS Framing, die 60100 Bytes kombinierten Overhead pro hinzufügen Nachricht, unabhängig vom Anwendungsprotokoll siehe TLS-Datensatzgröße. Dateneffizienz und Komprimierung Jede XHR-Anfrage kann über die normale HTTP-Verhandlung das optimale Übertragungscodierungsformat (z. B. gzip für textbasierte Daten) verhandeln. Ähnlich, weil SSE auf UTF-8only Transfers beschränkt ist, können die Ereignisstromdaten effizient komprimiert werden, indem gzip über die gesamte Sitzung angewendet wird. Mit WebSocket ist die Situation komplexer: WebSocket kann sowohl Text - als auch Binärdaten übertragen, und als Ergebnis ist es nicht sinnvoll, die gesamte Sitzung zu komprimieren. Die binären Nutzlasten können bereits komprimiert werden. Als Ergebnis muss WebSocket einen eigenen Komprimierungsmechanismus implementieren und sie selektiv auf jede Nachricht anwenden. Die gute Nachricht ist die HyBi-Arbeitsgruppe, die die pro-message Komprimierungserweiterung für das WebSocket-Protokoll entwickelt. Allerdings ist es noch nicht in einem der Browser verfügbar. Infolgedessen kann es, wenn die Anwendung ihre eigene Komprimierungslogik durch sorgfältige Optimierung ihrer binären Nutzlasten (siehe Decodierung von Binärdaten mit JavaScript) und die Implementierung einer eigenen Komprimierungslogik für textbasierte Nachrichten implementiert, einen hohen Byte Overhead auf den übertragenen Daten Chrome und Einige WebKit-basierte Browser unterstützen eine ältere Revision (per-Frame-Komprimierung) der Komprimierungserweiterung zum WebSocket-Protokoll siehe WebSocket Multiplexing und Compression im Wild. Benutzerdefinierte Anwendungsprotokolle Der Browser ist für HTTP-Datenübertragungen optimiert: Er versteht das Protokoll und bietet eine breite Palette an Diensten wie Authentifizierung, Caching, Komprimierung und vieles mehr. Infolgedessen erben XHR-Anfragen alle diese Funktionalität kostenlos. Im Gegensatz dazu ermöglicht das Streaming, benutzerdefinierte Protokolle zwischen Client und Server zu liefern, aber auf Kosten der Umgehung vieler Dienste, die vom Browser bereitgestellt werden: Der erste HTTP-Handshake kann in der Lage sein, einige Verhandlungen über die Parameter der Verbindung durchzuführen, aber einmal Die Sitzung ist etabliert, alle weiteren Daten, die zwischen dem Client und dem Server gestreamt werden, sind für den Browser undurchsichtig. Infolgedessen hat die Flexibilität, ein benutzerdefiniertes Protokoll zu liefern, auch seine Nachteile, und die Anwendung muss möglicherweise eine eigene Logik implementieren, um die fehlenden Lücken auszufüllen: Caching, State Management, Bereitstellung von Nachrichten-Metadaten und so weiter Das erste HTTP-Upgrade Handshake ermöglicht es dem Server, den vorhandenen HTTP-Cookie-Mechanismus zu nutzen, um den Benutzer zu validieren. Wenn die Validierung fehlschlägt, kann der Server das WebSocket-Upgrade ablehnen. Nutzung von Browser - und Intermediary-Caches Mit regulärem HTTP sind wesentliche Vorteile. Stellen Sie sich eine einfache Frage: Würde der Kunde vom Caching der empfangenen Daten profitieren oder könnte ein Vermittler die Auslieferung des Assets optimieren, wenn er ihn cache könnte. Zum Beispiel unterstützt WebSocket binäre Transfers, die es der Anwendung ermöglichen, beliebige Bildformate ohne Overheadnice zu streamen Win Die Tatsache, dass das Bild innerhalb eines benutzerdefinierten Protokolls geliefert wird, bedeutet, dass es nicht vom Browser-Cache oder einem Vermittler (zB einem CDN) zwischengespeichert wird. Infolgedessen können Sie unnötige Transfers zum Client und viel höheren Verkehr zu den Ursprungsservern verursachen. Die gleiche Logik gilt für alle anderen Datenformate: Video, Text und so weiter. Infolgedessen stellen Sie sicher, dass Sie den richtigen Transport für den Job wählen Eine einfache, aber effektive Strategie, um diese Bedenken zu adressieren könnte sein, um die WebSocket-Sitzung zu verwenden, um nicht-cachefähige Daten wie Echtzeit-Updates und Anwendungssteuerungsnachrichten zu liefern, die können Trigger XHR-Anfragen, um andere Assets über das HTTP-Protokoll abzurufen. Bereitstellung von WebSocket Infrastructure HTTP ist für kurze und bursty Transfers optimiert. Infolgedessen sind viele der Server, Proxies und andere Vermittler oft konfiguriert, um aggressiv Timeout Idle HTTP-Verbindungen, die natürlich genau das ist, was wir nicht für langlebige WebSocket-Sessions sehen wollen. Um dies zu beheben, gibt es drei Stücke zu beachten: Router, Load-Balancer und Proxies im eigenen Netzwerk Transparente und explizite Proxies im externen Netzwerk (zB ISP und Carrier Proxies) Router, Firewalls und Proxies im Clients Netzwerk Wir haben keine Kontrolle Über die Politik des Clients Netzwerk. In der Tat können einige Netzwerke WebSocket-Verkehr vollständig blockieren, weshalb Sie eine Fallback-Strategie benötigen. Ähnlich haben wir keine Kontrolle über die Proxies auf dem externen Netzwerk. Allerdings ist dies, wo TLS helfen kann Durch Tunneling über eine sichere End-to-End-Verbindung, kann WebSocket Verkehr alle Zwischenproxys umgehen. Die Verwendung von TLS verhindert nicht, dass der Vermittler eine Leerlauf-TCP-Verbindung abschaltet. In der Praxis erhöht sie jedoch die Erfolgsquote der Verhandlung der WebSocket-Sitzung erheblich und hilft oft auch, die Zeitüberschreitungsintervalle zu verlängern. Schließlich gibt es die Infrastruktur, die wir einsetzen und verwalten, die auch oft Aufmerksamkeit und Tuning erfordert. So einfach wie es ist, den Klienten oder externe Netzwerke zu beschuldigen, allzu oft ist das Problem nah an zu Hause. Jeder Load-Balancer, Router, Proxy und Webserver im Serving-Pfad muss abgestimmt sein, um langlebige Verbindungen zu ermöglichen. For example, Nginx 1.3.13 can proxy WebSocket traffic, but defaults to aggressive 60-second timeouts To increase the limit, we must explicitly define the longer timeouts: 60-minute inactivity timeout for tunnels The gotcha with the preceding example is the extra tunnel timeout. In HAProxy the connect. client. and server timeouts are applied only to the initial HTTP Upgrade handshake, but once the upgrade is complete, the timeout is controlled by the tunnel value. Nginx and HAProxy are just two of hundreds of different servers, proxies, and load balancers running in our data centers. We cant enumerate all the configuration possibilities in these pages. The previous examples are just an illustration that most infrastructure requires custom configuration to handle long-lived sessions. Hence, before implementing application keepalives, double-check your infrastructure first. Long-lived and idle sessions occupy memory and socket resources on all the intermediate servers. Hence, short timeouts are often justified as a security, resource, and operational precaution. Deploying WebSocket, SSE, and HTTP2, each of which relies on long-lived sessions, brings its own class of new operational challenges. Performance Checklist Deploying a high-performance WebSocket service requires careful tuning and consideration, both on the client and on the server. A short list of criteria to put on the agenda: Use secure WebSocket (WSS over TLS) for reliable deployments. Pay close attention to polyfill performance (if necessary). Leverage subprotocol negotiation to determine the application protocol. Optimize binary payloads to minimize transfer size. Consider compressing UTF-8 content to minimize transfer size. Set the right binary type for received binary payloads. Monitor the amount of buffered data on the client. Split large application messages to avoid head-of-line blocking. Leverage other transports where applicable. Last, but definitely not least, optimize for mobile Real-time push can be a costly performance anti-pattern on mobile handsets, where battery life is always at a premium. Thats not to say that WebSocket should not be used on mobile. To the contrary, it can be a highly efficient transport, but make sure to account for its requirements :17. WebSocket by Ilya Grigorik Chapter 17. WebSocket WebSocket enables bidirectional, message-oriented streaming of text and binary data between client and server. It is the closest API to a raw network socket in the browser. Except a WebSocket connection is also much more than a network socket, as the browser abstracts all the complexity behind a simple API and provides a number of additional services: Connection negotiation and same-origin policy enforcement Interoperability with existing HTTP infrastructure Message-oriented communication and efficient message framing Subprotocol negotiation and extensibility WebSocket is one of the most versatile and flexible transports available in the browser. The simple and minimal API enables us to layer and deliver arbitrary application protocols between client and serveranything from simple JSON payloads to custom binary message formatsin a streaming fashion, where either side can send data at any time. However, the trade-off with custom protocols is that they are, well, custom. The application must account for missing state management, compression, caching, and other services otherwise provided by the browser. There are always design constraints and performance trade-offs, and leveraging WebSocket is no exception. In short, WebSocket is not a replacement for HTTP, XHR, or SSE, and for best performance it is critical that we leverage the strengths of each transport. WebSocket is a set of multiple standards: the WebSocket API is defined by the W3C, and the WebSocket protocol (RFC 6455) and its extensions are defined by the HyBi Working Group (IETF). WebSocket API The WebSocket API provided by the browser is remarkably small and simple. Once again, all the low-level details of connection management and message processing are taken care of by the browser. To initiate a new connection, we need the URL of a WebSocket resource and a few application callbacks: Open a new secure WebSocket connection (wss) Optional callback, invoked if a connection error has occurred Optional callback, invoked when the connection is terminated Optional callback, invoked when a WebSocket connection is established Client-initiated message to the server A callback function invoked for each new message from the server Invoke binary or text processing logic for the received message The API speaks for itself. In fact, it should look very similar to the EventSource API we saw in the preceding chapter. This is intentional, as WebSocket offers similar and extended functionality. Having said that, there are a number of important differences as well. Lets take a look at them one by one. WebSocket protocol has undergone a number of revisions, implementation rollbacks, and security investigations. However, the good news is that the latest version (v13) defined by RFC6455 is now supported by all modern browsers. The only notable omission is the Android browser. For the latest status, see caniusewebsockets . Similar to the SSE polyfill strategy (Emulating EventSource with Custom JavaScript ), the WebSocket browser API can be emulated via an optional JavaScript library. However, the hard part with emulating WebSockets is not the API, but the transport As a result, the choice of the polyfill library and its fallback transport (XHR polling, EventSource, iframe polling, etc.) will have significant impact on the performance of an emulated WebSocket session. To simplify cross-browser deployment, popular libraries such as SockJS provide an implementation of WebSocket-like object in the browser but also go one step further by providing a custom server that implements support for WebSocket and a variety of alternative transports. The combination of a custom server and client is what enables seamless fallback: the performance suffers, but the application API remains the same. Other libraries, such as Socket. IO, go even further by implementing additional features, such as heartbeats, timeouts, support for automatic reconnects, and more, in addition to a multitransport fallback functionality. When considering a polyfill library or a real-time framework, such as Socket. IO, pay close attention to the underlying implementation and configuration of the client and server: always leverage the native WebSocket interface for best performance, and ensure that fallback transports meet your performance goals. WS and WSS URL Schemes The WebSocket resource URL uses its own custom scheme: ws for plain-text communication (e. g. ws:examplesocket ), and wss when an encrypted channel (TCPTLS) is required. Why the custom scheme, instead of the familiar http The primary use case for the WebSocket protocol is to provide an optimized, bi-directional communication channel between applications running in the browser and the server. However, the WebSocket wire protocol can be used outside the browser and could be negotiated via a non-HTTP exchange. As a result, the HyBi Working Group chose to adopt a custom URL scheme. Despite the non-HTTP negotiation option enabled by the custom scheme, in practice there are no existing standards for alternative handshake mechanisms for establishing a WebSocket session. Receiving Text and Binary Data WebSocket communication consists of messages and application code and does not need to worry about buffering, parsing, and reconstructing received data. For example, if the server sends a 1 MB payload, the applications onmessage callback will be called only when the entire message is available on the client. Further, the WebSocket protocol makes no assumptions and places no constraints on the application payload: both text and binary data are fair game. Internally, the protocol tracks only two pieces of information about the message: the length of payload as a variable-length field and the type of payload to distinguish UTF-8 from binary transfers. When a new message is received by the browser, it is automatically converted to a DOMString object for text-based data, or a Blob object for binary data, and then passed directly to the application. The only other option, which acts as performance hint and optimization for the client, is to tell the browser to convert the received binary data to an ArrayBuffer instead of Blob: Force an ArrayBuffer conversion when a binary message is received User agents can use this as a hint for how to handle incoming binary data: if the attribute is set to blob, it is safe to spool it to disk, and if it is set to arraybuffer, it is likely more efficient to keep the data in memory. Naturally, user agents are encouraged to use more subtle heuristics to decide whether to keep incoming data in memory or not The WebSocket API W3C Candidate Recommendation A Blob object represents a file-like object of immutable, raw data. If you do not need to modify the data and do not need to slice it into smaller chunks, then it is the optimal formate. g. you can pass the entire Blob object to an image tag (see the example in Downloading Data with XHR ). On the other hand, if you need to perform additional processing on the binary data, then ArrayBuffer is likely the better fit. Decoding Binary Data with JavaScript An ArrayBuffer is a generic, fixed-length binary data buffer. However, an ArrayBuffer can be used to create one or more ArrayBufferView objects, each of which can present the contents of the buffer in a specific format. For example, lets assume we have the following C-like binary data structure: Given an ArrayBuffer object of this type, we can create multiple views into the same buffer, each with its own offset and data type: Each view takes the parent buffer, starting byte offset, and number of elements to processthe offset is calculated based on the size of the preceding fields. As a result, ArrayBuffer and WebSocket give our applications all the necessary tools to stream and process binary data within the browser. Sending Text and Binary Data Once a WebSocket connection is established, the client can send and receive UTF-8 and binary messages at will. WebSocket offers a bidirectional communication channel, which allows message delivery in both directions over the same TCP connection: Send a UTF-8 encoded text message Send a UTF-8 encoded JSON payload Send the ArrayBuffer contents as binary payload Send the ArrayBufferView contents as binary payload Send the Blob contents as binary payload The WebSocket API accepts a DOMString object, which is encoded as UTF-8 on the wire, or one of ArrayBuffer, ArrayBufferView, or Blob objects for binary transfers. However, note that the latter binary options are simply an API convenience: on the wire, a WebSocket frame is either marked as binary or text via a single bit. Hence, if the application, or the server, need other content-type information about the payload, then they must use an additional mechanism to communicate this data. The send() method is asynchronous: the provided data is queued by the client, and the function returns immediately. As a result, especially when transferring large payloads, do not mistake the fast return for a signal that the data has been sent To monitor the amount of data queued by the browser, the application can query the bufferedAmount attribute on the socket: Subscribe to application updates (e. g. game state changes) Check the amount of buffered data on the client Send the next update if the buffer is empty The preceding example attempts to send application updates to the server, but only if the previous messages have been drained from the clients buffer. Why bother with such checks All WebSocket messages are delivered in the exact order in which they are queued by the client. As a result, a large backlog of queued messages, or even a single large message, will delay delivery of messages queued behind ithead-of-line blocking To work around this problem, the application can split large messages into smaller chunks, monitor the bufferedAmount value carefully to avoid head-of-line blocking, and even implement its own priority queue for pending messages instead of blindly queuing them all on the socket. Many applications generate multiple classes of messages: high-priority updates, such as control traffic, and low-priority updates, such as background transfers. To optimize delivery, the application should pay close attention to how and when each type of message is queued on the socket Subprotocol Negotiation WebSocket protocol makes no assumptions about the format of each message: a single bit tracks whether the message contains text or binary data, such that it can be efficiently decoded by the client and server, but otherwise the message contents are opaque. Further, unlike HTTP or XHR requests, which communicate additional metadata via HTTP headers of each request and response, there is no such equivalent mechanism for a WebSocket message. As a result, if additional metadata about the message is required, then the client and server must agree to implement their own subprotocol to communicate this data: The client and server can agree on a fixed message format upfronte. g. all communication will be done via JSON-encoded messages or a custom binary format, and necessary message metadata will be part of the encoded structure. If the client and server need to transfer different data types, then they can agree on a consistent message header, which can be used to communicate the instructions to decode the remainder of the payload. A mix of text and binary messages can be used to communicate the payload and metadata informatione. g. a text message can communicate an equivalent of HTTP headers, followed by a binary message with the application payload. This list is just a small sample of possible strategies. The flexibility and low overhead of a WebSocket message come at the cost of extra application logic. However, message serialization and management of metadata are only part of the problem Once we determine the serialization format for our messages, how do we ensure that both client and server understand each other, and how do we keep them in sync Thankfully, WebSocket provides a simple and convenient subprotocol negotiation API to address the second problem. The client can advertise which protocols it supports to the server as part of its initial connection handshake: Array of subprotocols to advertise during WebSocket handshake Check the subprotocol chosen by the server As the preceding example illustrates, the WebSocket constructor accepts an optional array of subprotocol names, which allows the client to advertise the list of protocols it understands or is willing to use for this connection. The specified list is sent to the server, and the server is allowed to pick one of the protocols advertised by the client. If the subprotocol negotiation is successful, then the onopen callback is fired on the client, and the application can query the protocol attribute on the WebSocket object to determine the chosen protocol. On the other hand, if the server does not support any of the client protocols advertised by the client, then the WebSocket handshake is incomplete: the onerror callback is invoked, and the connection is terminated. The subprotocol names are defined by the application and are sent as specified to the server during the initial HTTP handshake. Other then that, the specified subprotocol has no effect on the core WebSocket API. WebSocket Protocol The WebSocket wire protocol (RFC 6455) developed by the HyBi Working Group consists of two high-level components: the opening HTTP handshake used to negotiate the parameters of the connection and a binary message framing mechanism to allow for low overhead, message-based delivery of both text and binary data. The WebSocket Protocol attempts to address the goals of existing bidirectional HTTP technologies in the context of the existing HTTP infrastructure as such, it is designed to work over HTTP ports 80 and 443 However, the design does not limit WebSocket to HTTP, and future implementations could use a simpler handshake over a dedicated port without reinventing the entire protocol. WebSocket Protocol RFC 6455 WebSocket protocol is a fully functional, standalone protocol that can be used outside the browser. Having said that, its primary application is as a bidirectional transport for browser-based applications. Binary Framing Layer Client and server WebSocket applications communicate via a message-oriented API: the sender provides an arbitrary UTF-8 or binary payload, and the receiver is notified of its delivery when the entire message is available. To enable this, WebSocket uses a custom binary framing format (Figure 17-1 ), which splits each application message into one or more frames . transports them to the destination, reassembles them, and finally notifies the receiver once the entire message has been received. Figure 17-1. WebSocket frame: 214 bytes payload Frame The smallest unit of communication, each containing a variable-length frame header and a payload that may carry all or part of the application message. Message A complete sequence of frames that map to a logical application message. The decision to fragment an application message into multiple frames is made by the underlying implementation of the client and server framing code. Hence, the applications remain blissfully unaware of the individual WebSocket frames or how the framing is performed. Having said that, it is still useful to understand the highlights of how each WebSocket frame is represented on the wire: The first bit of each frame (FIN) indicates whether the frame is a final fragment of a message. A message may consist of just a single frame. The opcode (4 bits) indicates type of transferred frame: text (1) or binary (2) for transferring application data or a control frame such as connection close (8), ping (9), and pong (10) for connection liveness checks. The mask bit indicates whether the payload is masked (for messages sent from the client to the server only). Payload length is represented as a variable-length field: If 0125, then that is the payload length. If 126, then the following 2 bytes represent a 16-bit unsigned integer indicating the frame length. If 127, then the following 8 bytes represent a 64-bit unsigned integer indicating the frame length. Masking key contains a 32-bit value used to mask the payload. Payload contains the application data and custom extension data if the client and server negotiated an extension when the connection was established. The payload of all client-initiated frames is masked using the value specified in the frame header: this prevents malicious scripts executing on the client from performing a cache poisoning attack against intermediaries that may not understand the WebSocket protocol. For full details of this attack, refer to Talking to Yourself for Fun and Prot. presented at W2SP 2011. As a result, each server-sent WebSocket frame incurs 210 bytes of framing overhead. The client must also send a masking key, which adds an extra 4 bytes to the header, resulting in 614 bytes over overhead. No other metadata, such as header fields or other information about the payload, is available: all WebSocket communication is performed by exchanging frames that treat the payload as an opaque blob of application data. WebSocket Multiplexing and Head-of-Line Blocking WebSocket is susceptible to head-of-line blocking: messages can be split into one or more frames, but frames from different messages cant be interleaved, as there is no equivalent to a stream ID found in the HTTP 2.0 framing mechanism see Streams, Messages, and Frames ). As a result, a large message, even when split into multiple WebSocket frames, will block the delivery of frames associated with other messages. If your application is delivering latency-sensitive data, be careful about the payload size of each message and consider splitting large messages into multiple application messages The lack of multiplexing in core WebSocket specification also means that each WebSocket connection requires a dedicated TCP connection, which may become a potential problem for HTTP 1.x deployments due to a restricted number of connections per origin maintained by the browser see Exhausting Client and Server Resources . On the bright side, the new Multiplexing Extension for WebSockets developed by the HyBi Working Group addresses the latter limitation: With this extension, one TCP connection can provide multiple virtual WebSocket connections by encapsulating frames tagged with a channel ID The multiplexing extension maintains separate logical channels, each of which provides fully the logical equivalent of an independent WebSocket connection, including separate handshake headers. WebSocket Multiplexing (Draft 10) With this extension in place, multiple WebSocket connections (channels) can be multiplexed over the same TCP connection. However, each individual channel is still susceptible to head-of-line blocking Hence, one potential workaround is to use different channels, or dedicated TCP connections, to multiplex multiple messages in parallel. Finally, note that the preceding extension is necessary only for HTTP 1.x connections. While no official specification is yet available for transporting WebSocket frames with HTTP 2.0, doing so would be much easier: HTTP 2.0 has built-in stream multiplexing, and multiple WebSocket connections could be transported within a single session by encapsulating WebSocket frames within the HTTP 2.0 framing mechanism. Protocol Extensions WebSocket specification allows for protocol extensions: the wire format and the semantics of the WebSocket protocol can be extended with new opcodes and data fields. While somewhat unusual, this is a very powerful feature, as it allows the client and server to implement additional functionality on top of the base WebSocket framing layer without requiring any intervention or cooperation from the application code. What are some examples of WebSocket protocol extensions The HyBi Working Group, which is responsible for the development of the WebSocket specification, lists two official extensions in development: A Multiplexing Extension for WebSockets This extension provides a way for separate logical WebSocket connections to share an underlying transport connection. Compression Extensions for WebSocket A framework for creating WebSocket extensions that add compression functionality to the WebSocket Protocol. As we noted earlier, each WebSocket connection requires a dedicated TCP connection, which is inefficient. Multiplexing extension addresses this problem by extending each WebSocket frame with an additional channel ID to allow multiple virtual WebSocket channels to share a single TCP connection. Similarly, the base WebSocket specification provides no mechanism or provisions for compression of transferred data: each frame carries payload data as provided by the application. As a result, while this may not be a problem for optimized binary data structures, this can result in high byte transfer overhead unless the application implements its own data compression and decompression logic. In effect, compression extension enables an equivalent of transfer-encoding negotiation provided by HTTP. To enable one or more extensions, the client must advertise them in the initial Upgrade handshake, and the server must select and acknowledge the extensions that will be used for the lifetime of the negotiated connection. For a hands-on example, lets now take a closer look at the Upgrade sequence. WebSocket Multiplexing and Compression in the Wild As of mid-2013, WebSocket multiplexing is not yet supported by any popular browser. Similarly, there is limited support for compression: Google Chrome and the latest WebKit browsers may advertise an x-webkit-deflate-frame extension to the server. However, deflate-frame is based on an outdated revision of the standard and will be deprecated in the future. As the name implies, per-frame compresses the payload contents on a frame-by-frame basis, which is suboptimal for large messages that may be split between multiple frames. As a result, latest revisions of the compression extension have switched to per-message compressionthats the good news. The bad news is per-message compression is still experimental and is not yet available in any popular browser. As a result, the application should pay close attention to the content-type of transferred data and apply its own compression where applicable. That is, at least until native WebSocket compression support is available widely across all the popular browsers. This is especially important for mobile applications, where each unnecessary byte carries high costs to the user. HTTP Upgrade Negotiation The WebSocket protocol delivers a lot of powerful features: message-oriented communication, its own binary framing layer, subprotocol negotiation, optional protocol extensions, and more. As a result, before any messages can be exchanged, the client and server must negotiate the appropriate parameters to establish the connection. Leveraging HTTP to perform the handshake offers several advantages. First, it makes WebSockets compatible with existing HTTP infrastructure: WebSocket servers can run on port 80 and 443, which are frequently the only open ports for the client. Second, it allows us to reuse and extend the HTTP Upgrade flow with custom WebSocket headers to perform the negotiation: Sec-WebSocket-Version Sent by the client to indicate version (13 for RFC6455) of the WebSocket protocol it wants to use. If the server does not support the client version, then it must reply with a list of supported versions. Sec-WebSocket-Key An auto-generated key sent by the client, which acts as a challenge to the server to prove that the server supports the requested version of the protocol. Sec-WebSocket-Accept Server response that contains signed value of Sec-WebSocket-Key, proving that it understands the requested protocol version. Sec-WebSocket-Protocol Used to negotiate the application subprotocol: client advertises the list of supported protocols server must reply with a single protocol name. Sec-WebSocket-Extensions Used to negotiate WebSocket extensions to be used for this connection: client advertises supported extensions, and the server confirms one or more extensions by returning the same header. With that, we now have all the necessary pieces to perform an HTTP Upgrade and negotiate a new WebSocket connection between the client and server: Request to perform an upgrade to the WebSocket protocol WebSocket protocol version used by the client Auto-generated key to verify server protocol support Optional list of subprotocols specified by the application Optional list of protocol extensions supported by the client Just like any other client-initiated connection in the browser, WebSocket requests are subject to the same-origin policy: the browser automatically appends the Origin header to the upgrade handshake, and the remote server can use CORS to accept or deny the cross origin request see Cross-Origin Resource Sharing (CORS). To complete the handshake, the server must return a successful Switching Protocols response and confirm the selected options advertised by the client: 101 response code confirming WebSocket upgrade CORS header indicating opt-in for cross-origin connection Signed Key value proving protocol support Application subprotocol selected by the server List of WebSocket extensions selected by the server All RFC6455-compatible WebSocket servers use the same algorithm to compute the answer to the client challenge: the contents of the Sec-WebSocket-Key are concatenated with a unique GUID string defined in the standard, a SHA1 hash is computed, and the resulting string is base-64 encoded and sent back to the client. At a minimum, a successful WebSocket handshake must contain the protocol version and an auto-generated challenge value sent by the client, followed by a 101 HTTP response code (Switching Protocols) from the server with a hashed challenge-response to confirm the selected protocol version: Client must send Sec-WebSocket-Version and Sec-WebSocket-Key. Server must confirm the protocol by returning Sec-WebSocket-Accept. Client may send a list of application subprotocols via Sec-WebSocket-Protocol. Server must select one of the advertised subprotocols and return it via Sec-WebSocket-Protocol. If the server does not support any, then the connection is aborted. Client may send a list of protocol extensions in Sec-WebSocket-Extensions. Server may confirm one or more selected extensions via Sec-WebSocket-Extensions. If no extensions are provided, then the connection proceeds without them. Finally, once the preceding handshake is complete, and if the handshake is successful, the connection can now be used as a two-way communication channel for exchanging WebSocket messages. From here on, there is no other explicit HTTP communication between the client and server, and the WebSocket protocol takes over. Proxies, Intermediaries, and WebSockets In practice, for security and policy reasons, many users have a restricted set of open portsspecifically port 80 (HTTP), and port 443 (HTTPS). As a result, WebSocket negotiation is performed via the HTTP Upgrade flow to ensure the best compatibility with existing network policies and infrastructure. However, as we noted earlier in Proxies, Intermediaries, TLS, and New Protocols on the Web. many existing HTTP intermediaries may not understand the new WebSocket protocol, which can lead to a variety of failure cases: blind connection upgrades, unintended buffering of WebSocket frames, content modification without understanding of the protocol, misclassification of WebSocket traffic as compromised HTTP connections, and so on. The WebSocket Key and Accept handshake addresses some of these problems: it is a security policy against servers and intermediaries that may blindly upgrade the connection without actually understanding the WebSocket protocol. However, while this precaution addresses some deployment issues with explicit proxies, it is nonetheless insufficient for transparent proxies, which may analyze and modify the data on the wire without notice. The workaround Establish a secure end-to-end tunneli. e. use WSS By negotiating a TLS session prior to performing the HTTP Upgrade handshake, the client and server establish an encrypted tunnel, which resolves all of the previously listed concerns. This is especially true for mobile clients, whose traffic often passes through a variety of proxy services that may not play well with WebSocket. WebSocket Use Cases and Performance WebSocket API provides a simple interface for bidirectional, message-oriented streaming of text and binary data between client and server: pass in a WebSocket URL to the constructor, set up a few JavaScript callback functions, and we are up and runningthe rest is handled by the browser. Add to that the WebSocket protocol, which offers binary framing, extensibility, and subprotocol negotiation, and WebSocket becomes a perfect fit for delivering custom application protocols in the browser. However, just as with any discussion on performance, while the implementation complexity of the WebSocket protocol is hidden from the application, it nonetheless has important performance implications for how and when WebSocket should be used. WebSocket is not a replacement for XHR or SSE, and for best performance it is critical that we leverage the strengths of each transport Refer to XHR Use Cases and Performance and SSE Use Cases and Performance for a review of the performance characteristics of each transport. Request and Response Streaming WebSocket is the only transport that allows bidirectional communication over the same TCP connection (Figure 17-2 ): the client and server can exchange messages at will. As a result, WebSocket provides low latency delivery of text and binary application data in both directions. Figure 17-2. Communication flow of XHR, SSE, and WebSocket XHR is optimized for transactional request-response communication: the client sends the full, well-formed HTTP request to the server, and the server responds with a full response. There is no support for request streaming, and until the Streams API is available, no reliable cross-browser response streaming API. SSE enables efficient, low-latency server-to-client streaming of text-based data: the client initiates the SSE connection, and the server uses the event source protocol to stream updates to the client. The client cant send any data to the server after the initial handshake. Propagation and Queuing Latency Switching transports from XHR to SSE or WebSocket does not decrease the roundtrip between client and server Regardless of the transport, the propagation latency of the data packets is the same. However, aside from propagation latency, there is also the queuing latency . the time the message has to wait on the client or server before it can be routed to the other party. In the case of XHR polling, the queuing latency is a function of the client polling interval: the message may be available on the server, but it cannot be sent until the next client XHR request see Modeling Performance of XHR Polling. By contrast, both SSE and WebSocket use a persistent connection, which allows the server to dispatch the message (and client, in the case of WebSocket), the moment it becomes available. As a result, low-latency delivery for SSE and WebSocket is specifically referring to the elimination of message queuing latency. We have not yet figured out how to make WebSocket data packets travel faster than the speed of light Message Overhead Once a WebSocket connection is established, the client and server exchange data via the WebSocket protocol: application messages are split into one or more frames, each of which adds from 2 to 14 bytes of overhead. Further, because the framing is done via a custom binary format, both UTF-8 and binary application data can be efficiently encoded via the same mechanism. How does that compare with XHR and SSE SSE adds as little as 5 bytes per message but is restricted to UTF-8 content only see Event Stream Protocol. HTTP 1.x requests (XHR or otherwise) will carry an additional 500800 bytes of HTTP metadata, plus cookies see Measuring and Controlling Protocol Overhead. HTTP 2.0 compresses the HTTP metadata, which significantly reduces the overhead see Header Compression. In fact, if the headers do not change between requests, the overhead can be as low as 8 bytes Keep in mind that these overhead numbers do not include the overhead of IP, TCP, and TLS framing, which add 60100 bytes of combined overhead per message, regardless of the application protocol see TLS Record Size . Data Efficiency and Compression Every XHR request can negotiate the optimal transfer encoding format (e. g. gzip for text-based data), via regular HTTP negotiation. Similarly, because SSE is restricted to UTF-8only transfers, the event stream data can be efficiently compressed by applying gzip across the entire session. With WebSocket, the situation is more complex: WebSocket can transfer both text and binary data, and as a result it doesnt make sense to compress the entire session. The binary payloads may be compressed already As a result, WebSocket must implement its own compression mechanism and selectively apply it to each message. The good news is the HyBi working group is developing the per-message compression extension for the WebSocket protocol. However, it is not yet available in any of the browsers. As a result, unless the application implements its own compression logic by carefully optimizing its binary payloads (see Decoding Binary Data with JavaScript ) and implementing its own compression logic for text-based messages, it may incur high byte overhead on the transferred data Chrome and some WebKit-based browsers support an older revision (per-frame compression) of the compression extension to the WebSocket protocol see WebSocket Multiplexing and Compression in the Wild . Custom Application Protocols The browser is optimized for HTTP data transfers: it understands the protocol, and it provides a wide array of services, such as authentication, caching, compression, and much more. As a result, XHR requests inherit all of this functionality for free. By contrast, streaming allows us to deliver custom protocols between client and server, but at the cost of bypassing many of the services provided by the browser: the initial HTTP handshake may be able to perform some negotiation of the parameters of the connection, but once the session is established, all further data streamed between the client and server is opaque to the browser. As a result, the flexibility of delivering a custom protocol also has its downsides, and the application may have to implement its own logic to fill in the missing gaps: caching, state management, delivery of message metadata, and so on The initial HTTP Upgrade handshake does allow the server to leverage the existing HTTP cookie mechanism to validate the user. If the validation fails, the server can decline the WebSocket upgrade. Leveraging Browser and Intermediary Caches Using regular HTTP has significant advantages. Ask yourself a simple question: would the client benefit from caching the received data Or could an intermediary optimize the delivery of the asset if it could cache it For example, WebSocket supports binary transfers, which allows the application to stream arbitrary image formats with no overheadnice win However, the fact that the image is delivered within a custom protocol means that it wont be cached by the browser cache, or any intermediary (e. g. a CDN). As a result, you may incur unnecessary transfers to the client and much higher traffic to the origin servers. The same logic applies to all other data formats: video, text, and so on. As a result, make sure you choose the right transport for the job A simple but effective strategy to address these concerns could be to use the WebSocket session to deliver non-cacheable data, such as real-time updates and application control messages, which can trigger XHR requests to fetch other assets via the HTTP protocol. Deploying WebSocket Infrastructure HTTP is optimized for short and bursty transfers. As a result, many of the servers, proxies, and other intermediaries are often configured to aggressively timeout idle HTTP connections, which, of course, is exactly what we dont want to see for long-lived WebSocket sessions. To address this, there are three pieces to consider: Routers, load-balancers, and proxies within own network Transparent and explicit proxies in external network (e. g. ISP and carrier proxies) Routers, firewalls, and proxies within the clients network We have no control over the policy of the clients network. In fact, some networks may block WebSocket traffic entirely, which is why you may need a fallback strategy. Similarly, we dont have control over the proxies on the external network. However, this is where TLS may help By tunneling over a secure end-to-end connection, WebSocket traffic can bypass all the intermediate proxies. Using TLS does not prevent the intermediary from timing out an idle TCP connection. However, in practice, it significantly increases the success rate of negotiating the WebSocket session and often also helps to extend the connection timeout intervals. Finally, there is the infrastructure that we deploy and manage ourselves, which also often requires attention and tuning. As easy as it is to blame the client or external networks, all too often the problem is close to home. Each load-balancer, router, proxy, and web server in the serving path must be tuned to allow long-lived connections. For example, Nginx 1.3.13 can proxy WebSocket traffic, but defaults to aggressive 60-second timeouts To increase the limit, we must explicitly define the longer timeouts: Set 60-minute timeout between reads Set 60-minute timeout between writes Similarly, it is not uncommon to have a load balancer, such as HAProxy, in front of one or more Nginx servers. Not surprisingly, we need to apply similar explicit configuration here as welle. g. for HAProxy: 60-minute inactivity timeout for tunnels The gotcha with the preceding example is the extra tunnel timeout. In HAProxy the connect. client. and server timeouts are applied only to the initial HTTP Upgrade handshake, but once the upgrade is complete, the timeout is controlled by the tunnel value. Nginx and HAProxy are just two of hundreds of different servers, proxies, and load balancers running in our data centers. We cant enumerate all the configuration possibilities in these pages. The previous examples are just an illustration that most infrastructure requires custom configuration to handle long-lived sessions. Hence, before implementing application keepalives, double-check your infrastructure first. Long-lived and idle sessions occupy memory and socket resources on all the intermediate servers. Hence, short timeouts are often justified as a security, resource, and operational precaution. Deploying WebSocket, SSE, and HTTP 2.0, each of which relies on long-lived sessions, brings its own class of new operational challenges. Performance Checklist Deploying a high-performance WebSocket service requires careful tuning and consideration, both on the client and on the server. A short list of criteria to put on the agenda: Use secure WebSocket (WSS over TLS) for reliable deployments. Pay close attention to polyfill performance (if necessary). Leverage subprotocol negotiation to determine the application protocol. Optimize binary payloads to minimize transfer size. Consider compressing UTF-8 content to minimize transfer size. Set the right binary type for received binary payloads. Monitor the amount of buffered data on the client. Split large application messages to avoid head-of-line blocking. Leverage other transports where applicable. Last, but definitely not least, optimize for mobile Real-time push can be a costly performance anti-pattern on mobile handsets, where battery life is always at a premium. Thats not to say that WebSocket should not be used on mobile. To the contrary, it can be a highly efficient transport, but make sure to account for its requirements : With Safari, you learn the way you learn best. Holen Sie sich unbegrenzten Zugang zu Videos, Live-Online-Training, Lernpfade, Bücher, interaktive Tutorials und vieles mehr. Keine Kreditkarte benötigt
No comments:
Post a Comment