Web
Network Programming
JSON, Websocket
##
Overview of Today's Class - JSON - Network Programming - Fetch - NodeJS client - Demo (polling, SSE, Websocket) - Strict mode
##
Educational Objectives On completion of this part, students will be able to: - Read and write JSON data - Explain how a backend framework can be used to implement a chat application - Describe the differences between polling, long-polling, server-sent events, and Websockets - Implement a server that receives and sends messages - Explain the purpose of the `use strict` directive, the pros and cons of using it, and how it affects the behavior of JavaScript programs
Quiz
Forms and Validation
##
Question 1 Etant donné le formulaire suivant hébergé sur l'URL http://www.example.com/, quel est l'URL résultant d'un clique sur le bouton "Send"? ```html
``` - (A) `http://www.example.com/send.html` - (B) `http://www.example.com/send.html?firstname=John&lastname=` - (C) `http://www.example.com/submit.html` - (D) `http://www.example.com/submit.html?firstname=John&lastname=Doe` - (E) Aucune réponse correcte
##
Solution 1 Etant donné le formulaire suivant hébergé sur l'URL http://www.example.com/, quel est l'URL résultant d'un clique sur le bouton "Send"? ```html
``` Answer (B): the `value` attribute of an input element is used as a default value when the form is submitted, while the `placeholder` attribute only provides text that will be shown in the input field when it is empty.
##
Question 2 Quelle est la valeur retournée par la regex suivante? ```js console.log(/ab+c*d/.test("acd")); ``` - (A) `true` - (B) `false` - (C) `"acd"` - (D) `undefined` - (D) `null` - (F) Aucune réponse correcte Notes:
Answer (A): the `*` quantifier matches zero or more occurrences of the preceding element, while the `+` quantifier matches one or more occurrences of the preceding element. `"acd"` does not contain any `b`, hence the result is false. Also, `test` returns a boolean describing whether a match is found or not, not the matched string.
##
Question 3 Quelle est la valeur retournée par la regex suivante? ```js console.log(/[a-z]*/i.test("Hello")); ``` - (A) `true` - (B) `false` - (C) `"hello"` - (D) `undefined` - (E) `null` - (F) Aucune réponse correcte Notes:
Answer (A) Although `[a-z]` expectl only lowercase characters, the `i` flag makes the regex case insensitive, so the capital `H` is matched, and the result is true.
##
Question 4 Quelles sont les valeurs de groupe extraites avec la regex suivante? ```js console.log("ABC D E".matchAll(/([A-Z])/g)); ``` - (A) A - (B) ABC, D, E - (C) A, B, C, D, E - (D) A, B, C - (E) D, E - (F) Aucune réponse correcte Notes:
Réponse (C). `[A-Z]` matche exactement une seule lettre majuscule. Le fait que ce pattern soit entouré par des parenthèses en fait un groupe, il y a donc un groupe par lettre majuscule.
JavaScript Object Notation (JSON)
##
JavaScript Object Notation (JSON) JSON is - a *string formatting* standard for structured data, - *based* on the Javascript object syntax Used for data serialization (only handles objects, arrays, string, number, boolean, null), usually for further transmittion or storage. ```json { "firstname": "John", "lastname": "Doe", "age": 28, "interests": ["ski", "bike"] } ``` - Extension: `.json`, - MIME type: `application/json` https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON
##
JavaScript Object Notation (JSON) Note that JSON is a standard for how to format *strings*. Note also that it is different from Javascript Objects. The syntax of JSON is *inspired* from the syntax of Javascript Objects, but it is not the same. Also, JSON does not support functions, dates, or undefined.
##
Object to JSON (stringify) The `JSON` global object offers conversion functions. `JSON.stringify` converts a Javascript object to a JSON string: ```js // A JavaScript Object var person = { firstname: "John", lastname: "Doe", age: 28, interests: ["ski", "bike"], get_age: function() { return this.age; } }; // And its JSON representation console.log(JSON.stringify(person)); ``` Note that functions and the prototype are *not* serialized. Stringifying an instance of a `Person` class will thus loose that information.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
##
JSON to Object (Parse) `JSON.parse` converts a JSON string to a Javascript object: ```js // A JSON object var person = '{"firstname":"John","lastname":"Doe","age":28,"interests":["ski","bike"]}'; // And its Javascript representation console.log(JSON.parse(person)); ```
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
##
JSON is NOT JavaScript! Why does the following snippet results in a SyntaxError? ```js // A JSON Object? var person = '{firstname:"John",lastname:"Doe",age:28,interests:["ski","bike"]}'; // Uncaught SyntaxError: Unexpected token f in JSON at position 1 console.log(JSON.parse(person)); ``` Why is the following snippet considered harmful? ```js // DON'T DO THIS!!! eval('var person = {firstname:"John",lastname:"Doe",age:28,interests:["ski","bike"]}'); ``` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON Notes: The main difference between the syntax of JS and JSON is that JSON requires double quotes around property names and string values, while JS objects do not. A more subtle difference is that JSON does not allow trailing commas, while JS objects do. In the second example, we are effectively using the Javascript execution engine to parse an object, instead of the JSON parser. The JS execution engine is Turing complete, and can be made to execute anything, while the JSON parser is very limited, to only parse JSON.
##
JSON is NOT JavaScript! The main difference between the syntax of JS and JSON is that JSON requires double quotes around property names and string values, while JS objects do not. A more subtle difference is that JSON does not allow trailing commas, while JS objects do. In the second example, we are effectively using the Javascript execution engine to parse an object, instead of the JSON parser. The JS execution engine is Turing complete, and can be made to execute anything, while the JSON parser is very limited, to only parse JSON.
Network Programming
##
HTTP Recall that the Hypertext Transfer Protocol (HTTP) is a request/response protocol. **HTTP/1.0** had a **short-lived** connection model and allowed **persistent connection** with the `Connection: keep-alive` HTTP header. **HTTP/1.1**, the version of HTTP commonly used by Web browsers, introduced: - **Persistent connections** that allow to reuse a TCP connection to send and receive multiple requests and responses (modern browsers **enable** this by default); - **Pipelined connections** that allow to send multiple requests without waiting for the corresponding responses (modern browsers **do not enable** this by default); - **Chunked transfers** that allow to divide the data stream into a series of chunks that are received independently of each other; - **Protocol upgrades** that allow a client to ask the server for a change in the application protocol. https://www.ietf.org/rfc/rfc2616.txt
##
HTTP Connection management
https://en.wikipedia.org/wiki/HTTP_persistent_connection
##
Implementing an Interactive drawing application Follow this link : https://docs.beescreens.ch/tutorials/create-an-interactive-drawing-application/introduction/
##
Implementing a Chat Application You can clone the `example-chat` repository in the `web-classroom` organization. https://github.com/web-classroom/example-chat The following slides will be illustrated with these examples.
##
Polling - The browser **polls** the events at a fixed interval - The server returns an empty result if there are no new events and immediatly closes the connection - The function `setInterval` is typically used set the interval - **Limitation:** the interval introduces a delay
##
Long-Polling - The browser **polls** events - The server keeps the connection open, returns events as soon as they are available, and closes the connection when the client sends a new request - When receiving events the browser can immediately send a new request - **Limitation:** this method requires to perform several requests
##
Server-side Events (SSE) - The browser **listen** to events and keeps the connection open - The server returns events as they become available and keeps the connection open - The browser provides the **EventSource API** that manages reconnections - **Limitation:** this method allows to receive events but not to send them
https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
##
Websocket - The browser open a connection and `Upgrade` the protocol to websocket - Once the websocket connection is open the browser and the server are allowed to send events - The browser provides the **WebSocket API** that manages protocol upgrade - **Limitation:** this method requires a protocol upgrade
##
Websocket https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Examples WebSocket is a protocol that exists at the same layer as HTTP, but is a distinct protocol, hence the need to declare the url with `ws://`. There is also a secure equivalent of websocket, similarly to HTTPS for HTTP: WSS, for which the url begins with `wss://`.
Strict mode
##
History JS was initially meant to be easy to pick up, so they chose to give non-error semantics to scenarios that should otherwise be errors. With ECMAScript 5, they realized this can cause more trouble in the future, so they made these things actual errors. - More developer mistakes throw errors - Simplifications to how variable references are resolved - Simplifications of `eval` and `arguments` - Secure JS is easier to write - Anticipations for future ECMAScript versions
##
Clearer errors - Failing when assigning to undeclared variables (instead of creating a global one) - Failing when fails to assign to a property - Failing when `delete`ing things that cannot be - Failing on duplicate function parameters or property names - Octal literals now start with `0o`, and number literals may no longer start with `0` - Failing when trying to set a property on primitive values
##
Scope management - No more `with` statement - `eval` no longer leaks (`eval("var x;")` used to create variable `x` in the surrounding scope) - Functions can be block-scoped
##
Security improvements - `this` is `undefined` if not a method or constructor, rather than `globalThis` - No longer possible to walk the call stack
##
Usage ```js function regularFunc() { username = "Marie" console.log(username) } regularFunc() ``` ```js "use strict" function strictFunc() { username = "Marie" console.log(username) } strictFunc() // Uncaught ReferenceError: username is not defined ```