You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 5-network/11-websocket/article.md
+18-18
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
1
# WebSocket
2
2
3
-
The `WebSocket` protocol, described in the specification [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455) provides a way to exchange data between browser and server via a persistent connection. The data can be passed in both directions as "packets", without breaking the connection and additional HTTP-requests.
3
+
The `WebSocket` protocol, described in the specification [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455), provides a way to exchange data between browser and server via a persistent connection. The data can be passed in both directions as "packets", without breaking the connection and the need of additional HTTP-requests.
4
4
5
5
WebSocket is especially great for services that require continuous data exchange, e.g. online games, real-time trading systems and so on.
6
6
@@ -19,7 +19,7 @@ The `wss://` protocol is not only encrypted, but also more reliable.
19
19
20
20
That's because `ws://` data is not encrypted, visible for any intermediary. Old proxy servers do not know about WebSocket, they may see "strange" headers and abort the connection.
21
21
22
-
On the other hand, `wss://` is WebSocket over TLS, (same as HTTPS is HTTP over TLS), the transport security layer encrypts the data at sender and decrypts at the receiver. So data packets are passed encrypted through proxies. They can't see what's inside and let them through.
22
+
On the other hand, `wss://` is WebSocket over TLS, (same as HTTPS is HTTP over TLS), the transport security layer encrypts the data at the sender and decrypts it at the receiver. So data packets are passed encrypted through proxies. They can't see what's inside and let them through.
23
23
```
24
24
25
25
Once the socket is created, we should listen to events on it. There are totally 4 events:
When `new WebSocket(url)` is created, it starts connecting immediately.
74
74
75
-
During the connection the browser (using headers) asks the server: "Do you support Websocket?" And if the server replies "yes", then the talk continues in WebSocket protocol, which is not HTTP at all.
75
+
During the connection, the browser (using headers) asks the server: "Do you support Websocket?" And if the server replies "yes", then the talk continues in WebSocket protocol, which is not HTTP at all.
76
76
77
77

78
78
79
-
Here's an example of browser headers for request made by `new WebSocket("wss://javascript.info/chat")`.
79
+
Here's an example of browser headers for a request made by `new WebSocket("wss://javascript.info/chat")`.
-`Origin` -- the origin of the client page, e.g. `https://javascript.info`. WebSocket objects are cross-origin by nature. There are no special headers or other limitations. Old servers are unable to handle WebSocket anyway, so there are no compatibility issues. But `Origin` header is important, as it allows the server to decide whether or not to talk WebSocket with this website.
91
+
-`Origin` -- the origin of the client page, e.g. `https://javascript.info`. WebSocket objects are cross-origin by nature. There are no special headers or other limitations. Old servers are unable to handle WebSocket anyway, so there are no compatibility issues. But the `Origin` header is important, as it allows the server to decide whether or not to talk WebSocket with this website.
92
92
-`Connection: Upgrade` -- signals that the client would like to change the protocol.
93
93
-`Upgrade: websocket` -- the requested protocol is "websocket".
94
-
-`Sec-WebSocket-Key` -- a random browser-generated key for security.
94
+
-`Sec-WebSocket-Key` -- a random browser-generated key, used to ensure that the server supports WebSocket protocol. It's random to prevent proxies from caching any following communication.
95
95
-`Sec-WebSocket-Version` -- WebSocket protocol version, 13 is the current one.
96
96
97
97
```smart header="WebSocket handshake can't be emulated"
Here `Sec-WebSocket-Accept` is `Sec-WebSocket-Key`, recoded using a special algorithm. The browser uses it to make sure that the response corresponds to the request.
110
+
Here `Sec-WebSocket-Accept` is `Sec-WebSocket-Key`, recoded using a special algorithm. Upon seeing it, the browser understands that the server really does support the WebSocket protocol.
111
111
112
-
Afterwards, the data is transfered using WebSocket protocol, we'll see its structure ("frames") soon. And that's not HTTP at all.
112
+
Afterwards, the data is transferred using the WebSocket protocol, we'll see its structure ("frames") soon. And that's not HTTP at all.
113
113
114
114
### Extensions and subprotocols
115
115
116
116
There may be additional headers `Sec-WebSocket-Extensions` and `Sec-WebSocket-Protocol` that describe extensions and subprotocols.
117
117
118
118
For instance:
119
119
120
-
-`Sec-WebSocket-Extensions: deflate-frame` means that the browser supports data compression. An extension is something related to transferring the data, functionality that extends WebSocket protocol. The header `Sec-WebSocket-Extensions` is sent automatically by the browser, with the list of all extensions it supports.
120
+
-`Sec-WebSocket-Extensions: deflate-frame` means that the browser supports data compression. An extension is something related to transferring the data, functionality that extends the WebSocket protocol. The header `Sec-WebSocket-Extensions` is sent automatically by the browser, with the list of all extensions it supports.
121
121
122
-
-`Sec-WebSocket-Protocol: soap, wamp` means that we'd like to transfer not just any data, but the data in [SOAP](http://en.wikipedia.org/wiki/SOAP) or WAMP ("The WebSocket Application Messaging Protocol") protocols. WebSocket subprotocols are registered in the [IANA catalogue](http://www.iana.org/assignments/websocket/websocket.xml). So, this header describes data formats that we're going to use.
122
+
-`Sec-WebSocket-Protocol: soap, wamp` means that we'd like to transfer not just any data, but the data in [SOAP](https://en.wikipedia.org/wiki/SOAP) or WAMP ("The WebSocket Application Messaging Protocol") protocols. WebSocket subprotocols are registered in the [IANA catalogue](https://www.iana.org/assignments/websocket/websocket.xml). So, this header describes the data formats that we're going to use.
123
123
124
124
This optional header is set using the second parameter of `new WebSocket`. That's the array of subprotocols, e.g. if we'd like to use SOAP or WAMP:
125
125
@@ -173,7 +173,7 @@ In the browser, we directly work only with text or binary frames.
173
173
174
174
**WebSocket `.send()` method can send either text or binary data.**
175
175
176
-
A call `socket.send(body)` allows `body` in string or a binary format, including `Blob`, `ArrayBuffer`, etc. No settings required: just send it out in any format.
176
+
A call `socket.send(body)` allows `body` in string or a binary format, including `Blob`, `ArrayBuffer`, etc. No settings are required: just send it out in any format.
177
177
178
178
**When we receive the data, text always comes as string. And for binary data, we can choose between `Blob` and `ArrayBuffer` formats.**
-`code` is a special WebSocket closing code (optional)
222
222
-`reason` is a string that describes the reason of closing (optional)
223
223
224
-
Then the other party in `close` event handler gets the code and the reason, e.g.:
224
+
Then the other party in the `close` event handler gets the code and the reason, e.g.:
225
225
226
226
```js
227
227
// closing party:
@@ -249,7 +249,7 @@ There are other codes like:
249
249
250
250
The full list can be found in [RFC6455, §7.4.1](https://tools.ietf.org/html/rfc6455#section-7.4.1).
251
251
252
-
WebSocket codes are somewhat like HTTP codes, but different. In particular, any codes less than `1000` are reserved, there'll be an error if we try to set such a code.
252
+
WebSocket codes are somewhat like HTTP codes, but different. In particular, codes lower than `1000` are reserved, there'll be an error if we try to set such a code.
253
253
254
254
```js
255
255
// in case connection is broken
@@ -321,8 +321,8 @@ Server-side code is a little bit beyond our scope. Here we'll use Node.js, but y
321
321
The server-side algorithm will be:
322
322
323
323
1. Create `clients = new Set()` -- a set of sockets.
324
-
2. For each accepted websocket, add it to the set `clients.add(socket)` and setup`message` event listener to get its messages.
325
-
3. When a message received: iterate over clients and send it to everyone.
324
+
2. For each accepted websocket, add it to the set `clients.add(socket)` and set`message` event listener to get its messages.
325
+
3. When a message is received: iterate over clients and send it to everyone.
326
326
4. When a connection is closed: `clients.delete(socket)`.
327
327
328
328
```js
@@ -359,7 +359,7 @@ Here's the working example:
359
359
360
360
[iframe src="chat" height="100" zip]
361
361
362
-
You can also download it (upper-right button in the iframe) and run locally. Just don't forget to install [Node.js](https://nodejs.org/en/) and `npm install ws` before running.
362
+
You can also download it (upper-right button in the iframe) and run it locally. Just don't forget to install [Node.js](https://nodejs.org/en/) and `npm install ws` before running.
363
363
364
364
## Summary
365
365
@@ -383,6 +383,6 @@ Events:
383
383
384
384
WebSocket by itself does not include reconnection, authentication and many other high-level mechanisms. So there are client/server libraries for that, and it's also possible to implement these capabilities manually.
385
385
386
-
Sometimes, to integrate WebSocket into existing project, people run WebSocket server in parallel with the main HTTP-server, and they share a single database. Requests to WebSocket use `wss://ws.site.com`, a subdomain that leads to WebSocket server, while `https://site.com` goes to the main HTTP-server.
386
+
Sometimes, to integrate WebSocket into existing projects, people run a WebSocket server in parallel with the main HTTP-server, and they share a single database. Requests to WebSocket use `wss://ws.site.com`, a subdomain that leads to the WebSocket server, while `https://site.com` goes to the main HTTP-server.
387
387
388
388
Surely, other ways of integration are also possible.
0 commit comments