Sec Websocket Protocollo Binario Options
Comunicato stampa SEC mette in guardia gli investitori circa le opzioni binarie e Oneri della Società con sede a Cipro con venderli illegalmente negli Stati Uniti PER IL RILASCIO IMMEDIATO 2013-103 Washington, DC 6 giugno 2013 mdash Oggi la Securities and Exchange Commission ha messo in guardia gli investitori sui potenziali rischi di investimento in binario opzioni e ha incaricato una società con sede a Cipro con la vendita illegalmente agli investitori statunitensi. Le opzioni binarie sono titoli sotto forma di contratti di opzione il cui pagamento dipende dal fatto che l'attività sottostante - per esempio uno stock Companys - aumenta o diminuisce in valore. In tale un tutto-o struttura dei pagamenti nulla, gli investitori scommettere su un aumento del prezzo delle azioni di fronte due possibili risultati alla scadenza del contratto: o ricevono un importo predeterminato di soldi se il valore del bene è aumentato nel periodo fisso, o no soldi a tutti se è diminuita. La SEC sostiene che Banc de Binary Ltd. è stata offerta e la vendita di opzioni binarie per gli investitori di tutto il Stati Uniti senza aver prima registrazione dei titoli, come richiesto ai sensi delle leggi federali sui titoli. La società ha ampiamente sollecitato i clienti residenti negli Stati Uniti con la pubblicità attraverso i video di YouTube, e-mail spam e altre pubblicità su Internet-based. rappresentanti Banc de Binary hanno comunicato con gli investitori direttamente per telefono, e-mail, chat e messaggistica istantanea. Banc de Binary anche ha agito come un mediatore, quando l'offerta e la vendita di tali titoli, ma non è riuscito a registrarsi presso la SEC come un broker, come richiesto dalla legge degli Stati Uniti. La SEC e la Commodity Futures Trading Commission (CFTC) ha emesso un investitore Alert congiunto per mettere in guardia gli investitori circa i regimi di promozione fraudolente riguardanti opzioni binarie e le piattaforme di trading di opzioni binarie. Gran parte del mercato delle opzioni binarie opera attraverso piattaforme di trading basati su Internet che non sono necessariamente conformità alle normative statunitensi applicabili e possono essere impegnati in attività illegali. Solo perché le imprese straniere possono più facilmente comunicare con gli investitori americani non significa che dovrebbero aggirare le nostre leggi di lunga data che proteggono gli investitori, richiedendo la registrazione dei titoli, ha detto Andrew J. Ceresney, Co-Direttore della Divisione SECs dell'esecuzione. Banc de Binary contattato investitori statunitensi attraverso Internet e YouTube, ma completamente ignorato i requisiti di registrazione leggi sui titoli degli Stati Uniti. Noi aggressivamente combattere tale condotta non importa dove proviene. Secondo la denuncia SEC contro Banc de Binary depositata in tribunale federale in Nevada, l'azienda ha iniziato ad offrire e vendere le opzioni binarie per gli investitori degli Stati Uniti nel 2010. Banc de Binary investitori indotti a creare account con la società, deposito di denaro in tali conti, e poi l'acquisto di opzioni binarie cui sottostanti includono indici azionari e azionari. Banc de binarys sollecitazione degli investitori degli Stati Uniti ha avuto un discreto successo e ha attirato alcuni clienti con mezzi molto modesti. Per esempio, un investitore aveva un reddito mensile di 300 e un patrimonio netto inferiore a 25.000, e un altro cliente è stato incoraggiato a depositare ulteriori fondi nel suo conto di trading Banc de Binary anche dopo aver informato il rappresentante Banc de Binary che era senza lavoro con meno di 1000 nel suo conto corrente. La denuncia SEC cerca sboccatura più pregiudizio interessi, sanzioni pecuniarie, e ingiunzioni preliminari e permanenti contro Banc de Binary tra l'altro sollievo. La CFTC ha annunciato oggi una azione parallela contro Banc de Binary. L'indagine è stata condotta da SEC Leslie A. Hakala e C. Dabney ORiordan dell'Ufficio regionale di Los Angeles. Il contenzioso SEC sarà guidata da John W. Berry e la signora Hakala. La SEC apprezza l'assistenza della CFTC in questa materia. L'allarme degli investitori sulle opzioni binarie è stato emesso congiuntamente dall'Ufficio SECs di Investor Education and Advocacy e l'Ufficio CFTCs di Outreach dei consumatori. Il bollettino discute in dettaglio i potenziali rischi di investire in opzioni binarie, e mette in guardia gli investitori che non possono avere la piena salvaguardia dei titoli federali e le leggi delle materie prime se acquistare opzioni binarie non registrati che non sono soggetti al controllo delle autorità di regolamentazione degli Stati Uniti. Gli investitori devono essere consapevoli del potenziale di frode in questo settore, nonché della realtà che essi possono perdere il loro intero investimento, ha detto Lori Schock, direttore dell'Ufficio SECs di Investor Education and Advocacy. Noi incoraggiamo fortemente gli investitori di verificare lo sfondo di broker e consulenti e piattaforme di trading prima di prendere una decisione di investire. Se gli investitori smussano ottenere semplici informazioni di base, come se il professionista finanziario è stato registrato presso la SEC o FINRA, allora dovrebbero essere estremamente cauti. MaterialsChapter correlati 17. WebSocket WebSocket consente bidirezionale, orientato ai messaggi di streaming di testo e dati binari tra client e server. È l'API più vicina ad una presa di rete grezzo nel browser. Tranne una connessione WebSocket è anche molto più di una presa di rete, come il browser astrae la complessità dietro una semplice API e fornisce una serie di servizi aggiuntivi: Trattativa Collegamento e same-origin policy enforcement L'interoperabilità con l'infrastruttura esistente HTTP orientati ai messaggi di comunicazione e messaggio efficiente inquadrare subprotocol negoziazione e l'estensibilità WebSocket è uno dei mezzi di trasporto più versatili e flessibili disponibili nel browser. L'API semplice e minimale ci permette di sovrapporre e fornire protocolli applicativi arbitrarie tra client e serveranything da semplici carichi JSON al messaggio binario personalizzato formatsin una moda in streaming, in cui entrambi i lati può inviare i dati in qualsiasi momento. Tuttavia, il trade-off con protocolli personalizzati è che sono, bene, su misura. L'applicazione deve tenere conto di gestione mancante stato, compressione, caching, e altri servizi diversamente previsto dal browser. Ci sono sempre progettare vincoli e compromessi di prestazioni, e sfruttando WebSocket non fa eccezione. In breve, WebSocket non è un sostituto per HTTP, XHR, o SSE, e per le migliori prestazioni è fondamentale che si leva i punti di forza di ogni trasporto. WebSocket è un insieme di standard multipli: l'API WebSocket è definito dal W3C, e il protocollo WebSocket (RFC 6455) e le sue estensioni sono definiti dal gruppo di lavoro HyBi (IETF). WebSocket API L'API WebSocket fornito dal browser è notevolmente piccolo e semplice. Ancora una volta, tutti i dettagli di basso livello di gestione della connessione e l'elaborazione dei messaggi sono curati dal browser. Per avviare una nuova connessione, abbiamo bisogno l'URL di una risorsa WebSocket e un paio di callback di applicazione: Invia il contenuto Blob come payload binario L'API WebSocket accetta un oggetto DOMString, che è codificato come UTF-8 sul filo, o uno dei ArrayBuffer , ArrayBufferView, o Blob oggetti per i trasferimenti binari. Si noti tuttavia che le opzioni binarie ultime siano semplicemente un comodo API: sul filo, un telaio WebSocket o è contrassegnato come binario o testo tramite un singolo bit. Quindi, se l'applicazione, o il server, hanno bisogno di altre informazioni tipo di contenuto per il payload, allora devono usare un ulteriore meccanismo di comunicare questi dati. Il metodo send () è asincrona: I dati forniti è in coda da parte del cliente, e la funzione restituisce immediatamente. Come risultato, soprattutto quando il trasferimento di grandi carichi, non confondere il rapido ritorno di un segnale che i dati sono stati inviati Per monitorare la quantità di dati accodati dal browser, l'applicazione può interrogare l'attributo bufferedAmount sulla presa: invia il seguente Update se il buffer è vuoto l'esempio precedente tenta di inviare gli aggiornamenti delle applicazioni al server, ma solo se i messaggi precedenti sono stati drenati dal buffer clienti. Perché perdere tempo con questi controlli Tutti i messaggi websocket vengono consegnati nell'ordine esatto in cui sono messi in coda da parte del cliente. Di conseguenza, un arretrato di messaggi in coda, o anche un singolo messaggio di grandi dimensioni, sarà ritardare la consegna dei messaggi in coda dietro ithead-of-line blocco Per ovviare a questo problema, l'applicazione può dividere messaggi di grandi dimensioni in blocchi più piccoli, monitorare la bufferedAmount valore di cautela per evitare head-of-line blocco, e anche implementare la propria coda di priorità per i messaggi in attesa invece di ciecamente tutti in fila sul socket. Molte applicazioni generano più classi di messaggi: aggiornamenti ad alta priorità, come il controllo del traffico e gli aggiornamenti a bassa priorità, come i trasferimenti di fondo. Per ottimizzare la consegna, l'applicazione deve prestare molta attenzione a come e quando ogni tipo di messaggio è in coda sul protocollo di negoziazione WebSocket presa subprotocol non fornisce alcuna ipotesi circa il formato di ogni messaggio: un unico tracce bit se il messaggio contiene dati di testo o binari, tale che può essere efficientemente decodificato dal client e server, ma per il resto i contenuti del messaggio sono opache. Inoltre, a differenza di HTTP o XHR richieste, che comunicano metadati aggiuntivi tramite intestazioni HTTP di ogni richiesta e risposta, non vi è alcun meccanismo equivalente per un messaggio WebSocket. Di conseguenza, se è necessario un ulteriore metadati sul messaggio, il client e il server devono accettare di implementare il proprio subprotocol di comunicare questi dati: Il client e il server possono essere d'accordo su un formato upfronte. g messaggio fisso. tutte le comunicazioni sarà fatto tramite messaggi JSON-codificati o un formato binario personalizzato, e metadati messaggio necessario sarà parte della struttura codificata. Se il client e il server devono trasferire diversi tipi di dati, allora possono concordare un'intestazione messaggio coerente, che può essere utilizzato per comunicare le istruzioni per decodificare il resto del payload. Un mix di messaggi di testo e binari può essere utilizzato per comunicare il payload ei metadati informatione. g. un messaggio di testo può comunicare un equivalente di intestazioni HTTP, seguito da un messaggio binario con il carico utile applicazione. Questa lista è solo un piccolo esempio di possibili strategie. La flessibilità e basso overhead di un messaggio WebSocket venire a costo di logica dell'applicazione supplementare. Tuttavia, il messaggio serializzazione e gestione dei metadati sono solo una parte del problema Una volta che si determina il formato di serializzazione per i nostri messaggi, come possiamo garantire che sia client che server capiscono a vicenda, e come possiamo tenerli in sincronia Fortunatamente, WebSocket fornisce un semplice e conveniente API subprotocol trattativa per affrontare il secondo problema. Il cliente può pubblicizzare quali protocolli supporta al server come parte della sua stretta di mano collegamento iniziale: Array di subprotocols per pubblicizzare durante WebSocket stretta di mano Controllare il subprotocol scelto dal server come nell'esempio precedente illustra, il costruttore WebSocket accetta una matrice facoltativa di nomi subprotocol , che permette al cliente di pubblicizzare l'elenco dei protocolli capisce o è disposto a utilizzare per questa connessione. L'elenco specificato viene inviato al server, e il server è permesso di scegliere uno dei protocolli pubblicizzati dal cliente. Se la negoziazione protocollo secondario è successo, allora il callback SuApertura è sparato sul client, e l'applicazione può interrogare l'attributo protocollo sull'oggetto WebSocket per determinare il protocollo scelto. D'altra parte, se il server non supporta alcun protocollo client pubblicizzati dal cliente, quindi l'handshake WebSocket è incompleta: la callback onerror viene richiamato, e la connessione viene terminata. I nomi subprotocol sono definite con l'applicazione e vengono inviati come specificato al server durante l'handshake HTTP iniziale. Altri poi che, il subprotocol specificata non ha alcun effetto sul core API WebSocket. protocollo wire WebSocket Il protocollo WebSocket (RFC 6455) messo a punto dal gruppo di lavoro HyBi è costituito da due componenti di alto livello: la stretta di mano di apertura HTTP utilizzato per negoziare i parametri della connessione e un meccanismo di messaggio inquadratura binario per consentire basso overhead, messaggio - consegna a base di testo e dati binari. Il protocollo WebSocket cerca di affrontare gli obiettivi di tecnologie HTTP bidirezionali esistenti nel contesto delle infrastrutture HTTP esistente in quanto tale, esso è stato progettato per funzionare su porte HTTP 80 e 443 Tuttavia, il progetto non si limiterà WebSocket a HTTP, e le implementazioni futuro potrebbe usare una stretta di mano più semplice su una porta dedicata senza reinventare l'intero protocollo. - WebSocket protocollo RFC 6455 protocollo WebSocket è un completamente funzionale, protocollo autonoma che può essere utilizzato al di fuori del browser. Detto questo, la sua applicazione principale è come un trasporto bidirezionale per le applicazioni basate su browser. applicazioni Framing strato client e server di websocket binari comunicano tramite un API orientato ai messaggi: il mittente fornisce un UTF-8 o binario payload arbitraria, e il ricevitore viene notificato della sua consegna quando l'intero messaggio è disponibile. Per attivare questa, WebSocket utilizza un formato di frame binario personalizzato (figura 17-1), che si divide ogni messaggio applicazione in uno o più fotogrammi. li trasporta alla destinazione, li riassembla, ed infine informa il ricevitore una volta ricevuto l'intero messaggio. Figura 17-1. Telaio WebSocket: 214 byte payload Frame Il più piccola unità di comunicazione, ciascuno contenente nell'intestazione frame di lunghezza variabile e un carico utile che può portare tutto o parte del messaggio dell'applicazione. Messaggio Una sequenza completa di fotogrammi che mappano un messaggio logica applicazione. La decisione di frammentare un messaggio di applicazione in più frame è costituito dalla realizzazione di base del codice inquadratura client e server. Quindi, le applicazioni rimangono beatamente ignari dei singoli fotogrammi websocket o come viene eseguito l'inquadratura. Detto questo, è ancora utile per capire i punti salienti di come ogni fotogramma WebSocket è rappresentato sul filo: Il primo bit di ogni frame (FIN) indica se il telaio è un frammento finale di un messaggio. Un messaggio può essere costituito da un singolo frame. Il codice operativo (4 bit) indica il tipo di cornice trasferiti: testo (1) o binario (2) per il trasferimento dei dati delle applicazioni o un frame di controllo come la stretta connessione (8), ping (9), e Pong (10) per la vitalità collegamento controlli. Il bit maschera indica se il carico utile è mascherato (per i messaggi inviati dal client al server solo). Lunghezza Payload è rappresentato come un campo di lunghezza variabile: Se 0125, che poi è la lunghezza payload. Se 126, quindi i seguenti 2 byte rappresentano un intero senza segno a 16 bit che indica la lunghezza del telaio. Se 127, quindi i seguenti 8 byte rappresentano un intero senza segno a 64 bit che indica la lunghezza del telaio. Mascherare chiave contiene un valore a 32 bit utilizzato per mascherare il carico utile. Payload contiene i dati dati delle applicazioni e di estensione personalizzata se il client e il server negoziato un interno quando è stata stabilita la connessione. Il carico utile di tutti i frame avviata dal client è mascherato utilizzando il valore specificato nell'intestazione del frame: questo impedisce script dannosi esecuzione sul client di eseguire un attacco di cache poisoning nei confronti di intermediari che non può comprendere il protocollo WebSocket. Per tutti i dettagli di questo attacco, fare riferimento a Parlare con te per divertimento e Prot. presentato al W2SP 2011. Di conseguenza, ogni frame WebSocket server inviato incorre 210 byte di inquadrare in testa. Il cliente deve anche inviare una chiave di mascheramento, che aggiunge un extra di 4 byte per l'intestazione, con conseguente 614 byte oltre spese generali. Non ci sono altri metadati, come i campi di intestazione o altre informazioni riguardo il carico utile, è disponibile: tutte le comunicazioni WebSocket viene eseguita tramite lo scambio di frame che trattano il carico utile come un blob opaca dei dati delle applicazioni. WebSocket Multiplexing e Head-of-line Blocco WebSocket è suscettibile di head-of-line blocking: i messaggi possono essere divisi in uno o più fotogrammi, ma fotogrammi da diversi messaggi smussano essere intercalati, in quanto non vi è alcun equivalente a un ID flusso si trovano in il meccanismo di inquadramento HTTP2 vedere Streams, Messaggi, e cornici). Come risultato, un messaggio di grandi dimensioni, anche quando diviso in più frame websocket, blocca l'erogazione di frame associati con altri messaggi. Se l'applicazione è fornire dati sensibili alla latenza, essere attenti circa la dimensione del payload di ogni messaggio e pensare di dividere messaggi di grandi dimensioni in più messaggi applicativi La mancanza di multiplazione a specifiche del nucleo WebSocket significa anche che ogni connessione WebSocket richiede una connessione TCP dedicato, che può diventare un potenziale problema per HTTP1.x implementazioni a causa di un numero limitato di connessioni per l'origine mantenute dal browser vedere aspiranti client e risorse del server. Il lato positivo, la nuova estensione Multiplexing per WebSockets sviluppato dal gruppo di lavoro HyBi affronta quest'ultima limitazione: Con questa estensione, una connessione TCP in grado di fornire più connessioni websocket virtuali da cornici incapsulanti etichettati con un ID di canale L'estensione multiplexing mantiene canali logici separati , ciascuna delle quali fornisce pienamente l'equivalente logico di una connessione WebSocket indipendenti, incluse le intestazioni handshake separati. - WebSocket Multiplexing (Progetto 10) Con questa estensione in atto, più connessioni websocket (canali) può essere canalizzato sulla stessa connessione TCP. Tuttavia, ogni singolo canale è ancora suscettibile di testa-di-line blocco Quindi, una potenziale soluzione è quella di utilizzare canali diversi, o connessioni TCP dedicati, di multiplex più messaggi in parallelo. Infine, ricordiamo che l'estensione precedente è necessaria solo per le connessioni HTTP1.x. Mentre nessun specifica ufficiale è ancora disponibile per il trasporto di cornici websocket con HTTP2, così facendo sarebbe molto più facile: HTTP2 è incorporato nel flusso di multiplexing, e connessioni multiple websocket potrebbe essere trasportato all'interno di una singola sessione di incapsulando fotogrammi websocket all'interno del meccanismo HTTP2 inquadratura. Protocollo specifiche estensioni WebSocket consente per le estensioni di protocollo: il formato del filo e la semantica del protocollo WebSocket possono essere estese con nuovi codici operativi e campi di dati. Mentre un po 'insolita, questa è una caratteristica molto potente, in quanto consente il client e il server per implementare funzionalità aggiuntive sulla sommità dello strato di base inquadratura WebSocket senza richiedere alcun intervento o collaborazione da parte del codice dell'applicazione. Quali sono alcuni esempi di estensioni del protocollo WebSocket Il gruppo di lavoro HyBi, che è responsabile per lo sviluppo della specifica WebSocket, elenca due estensioni ufficiali in fase di sviluppo: Un'estensione Multiplexing per WebSockets Questa estensione fornisce un modo per i diversi collegamenti websocket logica di condividere un sottostante collegamento. Estensioni di compressione per WebSocket un quadro per la creazione di estensioni websocket che aggiungono funzionalità di compressione al protocollo WebSocket. Come abbiamo notato in precedenza, ogni connessione WebSocket richiede una connessione TCP dedicata, che è inefficiente. estensione Multiplexing affronta questo problema estendendo ogni fotogramma WebSocket con un ID canale aggiuntivo per consentire a più canali websocket virtuali di condividere una singola connessione TCP. Allo stesso modo, le specifiche di base WebSocket fornisce alcun meccanismo o disposizioni per la compressione dei dati trasferiti: ogni frame trasporta i dati di payload come previsto dall'applicazione. Come risultato, mentre questo non può essere un problema per strutture di dati binari ottimizzate, può causare un trasferimento testa alta byte meno che l'applicazione implementa sua logica compressione dei dati e la decompressione. In effetti, l'estensione di compressione consente un equivalente di negoziazione transfer-encoding fornito da HTTP. Per abilitare una o più estensioni, il cliente li deve promuovere nella stretta di mano aggiornamento iniziale, e il server deve selezionare e riconoscere le estensioni che verranno utilizzati per la durata della connessione negoziata. Per un esempio, hands-on, consente ora di dare un'occhiata più da vicino la sequenza di aggiornamento. WebSocket Multiplexing e compressione nel selvaggio come di metà del 2013, WebSocket multiplexing non è ancora supportato da tutti i browser popolare. Allo stesso modo, c'è un supporto limitato per la compressione: Google Chrome e le più recenti browser WebKit possono fare pubblicità un'estensione x-webkit-deflate-frame al server. Tuttavia, sgonfiare-frame si basa su una revisione non aggiornata del livello e diventerà obsoleto in futuro. Come suggerisce il nome, per-fotogramma comprime il contenuto payload su una base fotogramma per fotogramma, che è ottimale per i messaggi di grandi dimensioni che possono essere suddivisi tra più fotogrammi. Di conseguenza, le ultime revisioni della estensione di compressione sono passati a per-messaggio compressionthats la buona notizia. La cattiva notizia è per-messaggio di compressione è ancora in fase sperimentale e non è ancora disponibile in qualsiasi browser popolare. Di conseguenza, l'applicazione dovrebbe prestare particolare attenzione al tipo di contenuto dei dati trasferiti e applicare la propria compressione, se del caso. Cioè, almeno fino a quando il supporto di compressione WebSocket nativo è ampiamente disponibili in tutti i browser più diffusi. Ciò è particolarmente importante per le applicazioni mobili, in cui ogni byte inutili comporta costi elevati per l'utente. HTTP Aggiornamento negoziazione Il protocollo WebSocket offre un sacco di funzioni potenti: messaggio orientato alla comunicazione, proprio livello inquadratura binario, la negoziazione subprotocol, protocollo estensioni opzionali, e altro ancora. Di conseguenza, prima di eventuali messaggi possono essere scambiati, il client e il server devono negoziare i parametri appropriati per stabilire la connessione. Sfruttando HTTP per eseguire l'handshake offre diversi vantaggi. In primo luogo, si rende WebSockets compatibili con l'infrastruttura esistente: HTTP server websocket possono correre sulla porta 80 e 443, che sono spesso le uniche porte aperte per il cliente. In secondo luogo, ci permette di riutilizzare ed estendere il flusso di aggiornamento HTTP con le intestazioni websocket personalizzato per eseguire la negoziazione: Sec-WebSocket-versione inviata dal cliente per indicare la versione (13 per RFC6455) del protocollo WebSocket si vuole usare. Se il server non supporta la versione client, allora deve rispondere con un elenco delle versioni supportate. Sec-WebSocket-Key Una chiave auto-generata inviato dal client, che agisce come una sfida al server per dimostrare che il server supporta la versione richiesta del protocollo. risposta del server che contiene il valore della Sec-WebSocket-Key firmato, dimostrando che capisce la versione del protocollo richiesto Sec-WebSocket-Accept. Sec-WebSocket-protocollo utilizzato per negoziare il subprotocol applicazione: client pubblicizza l'elenco dei server di protocolli supportati devono rispondere con un unico nome del protocollo. Sec-WebSocket-estensioni usate per negoziare estensioni websocket da utilizzare per questa connessione: il client pubblicizza estensioni supportate, e il server conferma una o più estensioni restituendo la stessa intestazione. Con questo, ora abbiamo tutti i pezzi necessari per eseguire un aggiornamento HTTP e negoziare un nuovo collegamento WebSocket tra il client e il server: Tutti i server websocket RFC6455-compatibile utilizzano lo stesso algoritmo per calcolare la risposta alla sfida cliente: il contenuto della sec-WebSocket-Key sono concatenati con una stringa univoca GUID definito nello standard, un hash SHA1 è calcolata, e la stringa risultante è base 64 codificato e inviato al client. Come minimo, un WebSocket handshake successo deve contenere la versione del protocollo e un valore sfida generata automaticamente inviato dal client, seguito da un codice di risposta 101 HTTP (Protocolli di commutazione) dal server con un hash sfida-risposta per confermare il protocollo selezionato versione: cliente deve inviare Sec-WebSocket-Version e Sec-WebSocket-Key. Server deve confermare il protocollo restituendo Sec-WebSocket-Accept. Cliente può inviare un elenco di subprotocols applicazione tramite Sec-WebSocket-protocollo. Server deve selezionare una delle subprotocols pubblicizzati e restituirlo via Sec-WebSocket-protocollo. Se il server non supporta alcuna, la connessione viene interrotta. Cliente può inviare un elenco di estensioni di protocollo in Sec-WebSocket-estensioni. Server può confermare una o più estensioni selezionate tramite Sec-WebSocket-estensioni. Se non sono forniti estensioni, allora la connessione procede senza. Infine, una volta che il handshake precedente è completa e se la stretta di mano è riuscita, il collegamento può ora essere utilizzato come canale di comunicazione bidirezionale per scambiare messaggi websocket. Da qui in poi, non c'è altra comunicazione esplicita HTTP tra il client e il server, e il protocollo WebSocket prende il sopravvento. Proxy, intermediari, e WebSockets In pratica, per ragioni di sicurezza e di politica, molti utenti hanno una serie limitata di aprire la porta portsspecifically 80 (HTTP), e la porta 443 (HTTPS). Di conseguenza, WebSocket negoziazione avviene tramite il flusso HTTP aggiornamento per garantire la migliore compatibilità con le politiche di rete esistenti e le infrastrutture. Tuttavia, come abbiamo notato in precedenza nel proxy, intermediari, TLS, e nuovi protocolli sul Web. molti intermediari HTTP esistenti non possono capire il nuovo protocollo WebSocket, che può portare a una varietà di casi di fallimento: gli aggiornamenti di collegamento ciechi, il buffering non intenzionale di fotogrammi WebSocket, modifica dei contenuti, senza la comprensione del protocollo, errata classificazione del traffico WebSocket come connessioni HTTP compromessi, e presto. La chiave WebSocket e accettare indirizzi stretta di mano alcuni di questi problemi: si tratta di una politica di sicurezza contro i server e gli intermediari che possono aggiornare alla cieca la connessione senza realmente capire il protocollo WebSocket. Tuttavia, mentre questa precauzione risolve alcuni problemi di implementazione con i proxy espliciti, è comunque insufficiente per i proxy trasparenti, che possono analizzare e modificare i dati sul filo senza preavviso. La soluzione Stabilire un sicuro tunneli. e end-to-end. utilizzare WSS Negoziando una sessione TLS prima di eseguire l'aggiornamento stretta di mano HTTP, il client e il server di stabilire un tunnel crittografato, che risolve tutti i problemi elencati in precedenza. Questo è particolarmente vero per i client mobili, il cui traffico passa spesso attraverso una varietà di servizi di proxy che non possono giocare bene con WebSocket. WebSocket casi d'uso e prestazioni WebSocket API fornisce una semplice interfaccia per bidirezionale, orientato ai messaggi di streaming di testo e dati binari tra client e server: passiamo in un URL WebSocket al costruttore, impostare alcune funzioni di callback JavaScript, e noi siamo su e resto runningthe viene gestito dal browser. A questo si aggiunge il protocollo WebSocket, che offre inquadramento binario, estensibilità, e negoziazione subprotocol, e WebSocket diventa una misura perfetta per la consegna di protocolli applicativi personalizzati nel browser. Tuttavia, proprio come con qualsiasi discussione sulle prestazioni, mentre la complessità implementazione del protocollo WebSocket è nascosto dall'applicazione, che ha comunque implicazioni importanti prestazioni per come e quando WebSocket dovrebbe essere usato. WebSocket non è un sostituto per XHR o SSE, e per le migliori prestazioni è fondamentale che si leva i punti di forza di ogni trasporto, fare riferimento alla XHR casi d'uso e le prestazioni e SSE casi d'uso e le prestazioni per una revisione delle caratteristiche prestazionali di ogni trasporto. Richiesta e risposta Streaming WebSocket è l'unico mezzo di trasporto che consente la comunicazione bidirezionale sulla stessa connessione TCP (Figura 17-2): il client e il server possono scambiare messaggi a volontà. Come risultato, WebSocket fornisce bassa consegna latenza del testo e applicazioni dati binari in entrambe le direzioni. Figura 17-2. flusso di comunicazione di XHR, SSE, e WebSocket XHR è ottimizzato per la comunicazione di richiesta-risposta transazionale: il client invia la piena, richiesta HTTP ben formato al server, e il server risponde con una risposta completa. Non vi è alcun supporto per la richiesta di streaming, e fino a quando l'API Streams è disponibile, non è affidabile risposta cross-browser in streaming API. SSE permette efficiente, a bassa latenza Streaming Server-to-client di dati basato su testo: il cliente avvia la connessione SSE, e il server utilizza il protocollo origine evento per trasmettere gli aggiornamenti al client. Il client cant inviare tutti i dati al server dopo la stretta di mano iniziale. Propagazione e Queuing latenza di commutazione trasporti da XHR a SSE o WebSocket non diminuisce l'andata e ritorno tra client e server, indipendentemente dal trasporto, la latenza di propagazione dei pacchetti di dati è la stessa. Tuttavia, a parte la latenza propagazione, c'è anche la latenza accodamento. il tempo il messaggio deve aspettare sul client o sul server prima di poter essere instradato verso l'altra parte. Nel caso di XHR polling, la latenza di accodamento è una funzione dell'intervallo client polling: il messaggio può essere disponibile sul server, ma non può essere inviato fino al successivo client richiesta XHR vedere Modellazione prestazioni di XHR Polling. Al contrario, sia SSE e WebSocket utilizzano una connessione permanente, che consente al server di spedire il messaggio (e client, nel caso di WebSocket), nel momento in cui diventa disponibile. Di conseguenza, la consegna a bassa latenza per SSE e WebSocket è specificamente riferisce all'eliminazione della latenza accodamento messaggi. Non abbiamo ancora capito come fare pacchetti di dati WebSocket viaggiare più veloce della velocità del Messaggio luce Overhead volta che la connessione WebSocket è stabilito, i dati dei clienti ed Exchange Server tramite il protocollo WebSocket: messaggi dell'applicazione sono divisi in uno o più fotogrammi, ciascuno di cui aggiunge da 2 a 14 byte di overhead. Inoltre, poiché l'inquadratura avviene tramite un formato binario personalizzato, sia i dati UTF-8 e delle applicazioni binarie possono essere codificati in modo efficiente tramite lo stesso meccanismo. Come si confronta con XHR e SSE SSE aggiunge un minimo di 5 byte per messaggio, ma è limitato ai contenuti UTF-8 solo vedere Event Streaming Protocol. richieste HTTP1.x (XHR o altro) porterà un ulteriore 500800 byte di metadati HTTP, oltre a biscotti consultare Misurazione e Controllo protocollo Overhead. HTTP2 comprime i metadati HTTP, che riduce in modo significativo le spese generali vedere compressione intestazione. Infatti, se le intestazioni non cambiano tra le richieste, il sovraccarico può essere a partire da 8 byte Tenete a mente che questi numeri generali non comprendono il sovraccarico di IP, TCP e TLS inquadratura, che aggiungono 60100 byte di overhead combinato per messaggio, indipendentemente dal protocollo applicazione leggere TLS Record Size. Efficienza dei dati e la richiesta di compressione Ogni XHR possono negoziare il formato di codifica trasferimento ottimale (ad esempio gzip per i dati basati su testo), tramite regolare negoziazione HTTP. Allo stesso modo, perché SSE è limitato ai trasferimenti UTF-8only, i dati di flusso di eventi possono essere efficacemente compressi applicando gzip attraverso l'intera sessione. Con WebSocket, la situazione è più complessa: WebSocket può trasferire entrambi i dati di testo e binari, e come risultato si pretende molto senso per comprimere l'intera sessione. I payload binari possono essere compressi già Come risultato, WebSocket deve eseguire il proprio meccanismo di compressione e selettivamente applicarlo a ciascun messaggio. La buona notizia è il gruppo di lavoro HyBi sta sviluppando l'estensione di compressione per-messaggio per il protocollo WebSocket. Tuttavia, non è ancora disponibile in qualsiasi browser. Di conseguenza, a meno che l'applicazione implementa la propria logica di compressione ottimizzando accuratamente i suoi carichi utili binari (vedi decodifica dei dati binari con JavaScript) e l'attuazione di una sua logica di compressione per i messaggi basati su testo, si può incorrere in alto byte di overhead sulla trasferito Chrome dati e alcuni browser basati su WebKit supportano un vecchio (compressione per-frame) revisione della estensione di compressione al protocollo WebSocket vedere WebSocket Multiplexing e compressione in natura. Personalizzata Applicazione Protocolli Il browser è ottimizzato per trasferimenti di dati HTTP: capisce il protocollo, e fornisce una vasta gamma di servizi, come ad esempio l'autenticazione, il caching, la compressione, e molto altro ancora. Di conseguenza, le richieste XHR ereditano tutte queste funzionalità gratuitamente. Per contro, lo streaming ci permette di fornire protocolli personalizzati tra client e server, ma al costo di bypassare molti dei servizi forniti dal browser: l'handshake HTTP iniziale può essere in grado di eseguire alcune negoziazione dei parametri della connessione, ma una volta la sessione è stabilito, tutti gli altri dati in streaming tra il client e il server è opaco al browser. Di conseguenza, la flessibilità di fornire un protocollo personalizzato ha anche i suoi lati negativi, e l'applicazione potrebbe essere necessario implementare una sua logica di colmare le lacune mancanti: caching, gestione dello stato, di consegna dei metadati messaggio, e così via La aggiornamento HTTP iniziale stretta di mano non consentire al server di sfruttare il meccanismo dei cookie HTTP esistenti per convalidare l'utente. Se la convalida non riesce, il server può rifiutare l'aggiornamento WebSocket. Sfruttando Browser e cache di intermediazione Utilizzando HTTP regolare ha vantaggi significativi. Ponetevi una domanda semplice: sarebbe il beneficio client da caching dei dati ricevuti O potrebbe un intermediario ottimizzare l'erogazione del bene se potesse memorizzare nella cache è, ad esempio, WebSocket supporta i trasferimenti binari, che permette l'applicazione per lo streaming formati di immagine arbitrarie senza overheadnice vincere Tuttavia, il fatto che l'immagine viene consegnato entro un protocollo personalizzato significa che è solito essere memorizzati nella cache dalla cache del browser, o qualsiasi intermediario (per esempio, un CDN). Come risultato, si può incorrere trasferimenti non necessari per il cliente e il traffico molto superiore ai server di origine. La stessa logica si applica a tutti gli altri formati di dati: video, testo e così via. Di conseguenza, assicurarsi di scegliere il trasporto giusta per il lavoro Una strategia semplice ma efficace per affrontare questi problemi potrebbe essere quella di utilizzare la sessione WebSocket per fornire dati non memorizzabili nella cache, come ad esempio aggiornamenti in tempo reale ei messaggi di controllo delle applicazioni, che possono grilletto XHR richieste per andare a prendere altri beni tramite il protocollo HTTP. Distribuzione WebSocket infrastrutture HTTP è ottimizzato per i trasferimenti brevi e impulsivi. Come risultato, molti dei server, proxy e altri intermediari sono spesso configurati per timeout aggressivamente connessioni HTTP inattive, che, naturalmente, è esattamente ciò che non vogliamo vedere di sessioni websocket di lunga durata. Per far fronte a questo, ci sono tre pezzi da considerare: router, load-balancer, e proxy all'interno di una propria rete proxy trasparenti ed esplicite in rete esterna (ad esempio, ISP e carrier proxy) router, firewall e proxy all'interno della rete client non abbiamo alcun controllo sulla politica della rete client. In realtà, alcune reti potrebbero bloccare il traffico WebSocket del tutto, che è il motivo per cui potrebbe essere necessario una strategia di ripiego. Allo stesso modo, noi non hanno controllo sui proxy sulla rete esterna. Tuttavia, questo è dove TLS può aiutare Con il tunneling tramite una connessione sicura end-to-end, il traffico WebSocket possono ignorare tutti i proxy intermedio. Utilizzando TLS non impedisce l'intermediario dal timeout di una connessione TCP inattiva. Tuttavia, in pratica, aumenta in modo significativo il tasso di successo di negoziare la sessione WebSocket e spesso aiuta anche a prolungare gli intervalli di timeout di connessione. Infine, vi è l'infrastruttura che abbiamo implementare e gestire noi stessi, che spesso richiede attenzione e messa a punto. Facile come è quello di dare la colpa al cliente o reti esterne, troppo spesso il problema è vicino a casa. Ogni bilanciamento del carico, router, proxy e web server nel percorso di servire devono essere sintonizzati per consentire le connessioni di lunga durata. 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. Ottenere un accesso illimitato ai video, formazione online dal vivo, percorsi didattici, libri, tutorial interattivi e altro ancora. Nessuna carta di credito richiesta
Comments
Post a Comment