HTML and CSS Reference
In-Depth Information
You have already taken a glimpse of transmitting plain text data in the previous
chapters, where you exchanged simple chat messages. Apart from this, strings are
tremendously helpful when dealing with human-readable data formats such as XML
and JSON .
Remember that whenever the onmessage event is raised, the client needs to check
the data type and act accordingly. JavaScript can easily determine that a data type
is of string type using the strict equal operator (that is, === ).
socket.onmessage = function(event) {
if (typeof === "string") {
console.log("Received string data.");
If you have an average experience with core JavaScript, you'll probably notice that
you could have used the following expression instead:
if ( instanceof String)
Although this code is pretty valid, it wouldn't work in your case. The reason is that the
instanceof expression requires the object on the left to have been created using
the JavaScript string constructor. In your case, the data is generated from the server,
so you can only determine their underlying type instead of their JavaScript class.
JSON ( JavaScript Object Notation ) is a lightweight format for transferring human-
readable data between computers. It is structured in key-value pairs, usually de-
scribing properties and values. Due to its efficiency, JSON is the dominant format for
transferring data between server and client. The most popular RESTful APIs, includ-
ing Facebook, Twitter, and Github, nowadays fully support JSON. Moreover, JSON
is a subset of JavaScript, so you can parse it immediately without using external
Search WWH ::

Custom Search