Skip to content

Commit c49cdb0

Browse files
committed
Update "WebSocket" article
1 parent 1e5ed54 commit c49cdb0

File tree

3 files changed

+20
-19
lines changed

3 files changed

+20
-19
lines changed

5-network/11-websocket/article.md

+18-18
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# WebSocket
22

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.
44

55
WebSocket is especially great for services that require continuous data exchange, e.g. online games, real-time trading systems and so on.
66

@@ -19,7 +19,7 @@ The `wss://` protocol is not only encrypted, but also more reliable.
1919

2020
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.
2121

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.
2323
```
2424
2525
Once the socket is created, we should listen to events on it. There are totally 4 events:
@@ -56,7 +56,7 @@ socket.onclose = function(event) {
5656
};
5757
5858
socket.onerror = function(error) {
59-
alert(`[error] ${error.message}`);
59+
alert(`[error]`);
6060
};
6161
```
6262

@@ -72,11 +72,11 @@ Now let's talk more in-depth.
7272

7373
When `new WebSocket(url)` is created, it starts connecting immediately.
7474

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.
7676

7777
![](websocket-handshake.svg)
7878

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")`.
8080

8181
```
8282
GET /chat
@@ -88,10 +88,10 @@ Sec-WebSocket-Key: Iv8io/9s+lYFgZWcXczP8Q==
8888
Sec-WebSocket-Version: 13
8989
```
9090

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 `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.
9292
- `Connection: Upgrade` -- signals that the client would like to change the protocol.
9393
- `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.
9595
- `Sec-WebSocket-Version` -- WebSocket protocol version, 13 is the current one.
9696

9797
```smart header="WebSocket handshake can't be emulated"
@@ -107,19 +107,19 @@ Connection: Upgrade
107107
Sec-WebSocket-Accept: hsBlbuDTkk24srzEOTBUlZAlC2g=
108108
```
109109

110-
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.
111111

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.
113113

114114
### Extensions and subprotocols
115115

116116
There may be additional headers `Sec-WebSocket-Extensions` and `Sec-WebSocket-Protocol` that describe extensions and subprotocols.
117117

118118
For instance:
119119

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.
121121

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.
123123

124124
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:
125125

@@ -173,7 +173,7 @@ In the browser, we directly work only with text or binary frames.
173173
174174
**WebSocket `.send()` method can send either text or binary data.**
175175
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.
177177
178178
**When we receive the data, text always comes as string. And for binary data, we can choose between `Blob` and `ArrayBuffer` formats.**
179179
@@ -221,7 +221,7 @@ socket.close([code], [reason]);
221221
- `code` is a special WebSocket closing code (optional)
222222
- `reason` is a string that describes the reason of closing (optional)
223223

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.:
225225

226226
```js
227227
// closing party:
@@ -249,7 +249,7 @@ There are other codes like:
249249

250250
The full list can be found in [RFC6455, §7.4.1](https://tools.ietf.org/html/rfc6455#section-7.4.1).
251251

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.
253253

254254
```js
255255
// 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
321321
The server-side algorithm will be:
322322

323323
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.
326326
4. When a connection is closed: `clients.delete(socket)`.
327327

328328
```js
@@ -359,7 +359,7 @@ Here's the working example:
359359

360360
[iframe src="chat" height="100" zip]
361361

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.
363363

364364
## Summary
365365

@@ -383,6 +383,6 @@ Events:
383383

384384
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.
385385

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.
387387

388388
Surely, other ways of integration are also possible.

5-network/11-websocket/demo.view/server.js

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ function accept(req, res) {
2121

2222
function onConnect(ws) {
2323
ws.on('message', function (message) {
24+
message = message.toString();
2425
let name = message.match(/([\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]+)$/gu) || "Guest";
2526
ws.send(`Hello from server, ${name}!`);
2627

Loading

0 commit comments

Comments
 (0)