HTML and CSS Reference
In-Depth Information
ws.onclose = function() {
messageContainer.innerHTML += "Connection is closed...";
};
Figure 11-2. Running the WebSocket echo server
Encoding Data
As mentioned earlier, WebSockets are bidirectional pipes. A WebSocket does not examine the content of the inbound
and outbound streams; it only ensures that the data reach their destination on each end. This is not a problem if
the data received are merely being echoed or lightly processed. For anything more complex, you will send discrete
packets of information to the server. Not only does this allow you to process the information better, but it also
eliminates errors caused by receiving information in the wrong order, a significant benefit.
Luckily, JavaScript already has a built-in type that you can use to send data, an Object . To send and receive
JavaScript Object Notation (JSON) data on the client, you have to serialize and deserialize it, that is, convert a JSON
object to a string and vice versa, with JSON.stringify and JSON.parse .
In the onopen function in Listing 11-6, you create an object and then serialize it to JSON. You need to do this
because the WebSocket protocol has no concept of structured data.
 
Search WWH ::




Custom Search