Books
BOOK
WebSocket Events
The API for WebSocket is based around events.
WebSocket fires four events, which are available from the JavaScript API and defined by the W3C:
openmessageerrorclose
With JavaScript, you listen for these events to fire either with the handler on<eventname>, or the addEventListener() method. Your code will provide a callback that will execute every time that event gets fired.
Breakdown of the Table
| Event Handler | Event Type |
|---|---|
onopen |
open |
onmessage |
message |
onerror |
error |
onclose |
close |
Each event handler is a property on the WebSocket object that lets you define a function to run when that event occurs.
BOOK
WebSocket Methods
The creators of WebSocket kept its methods pretty simple. There are only two:
send()&close().
Method: Send
Method: Close
BOOK
WebSocket Attributes
When the event for open is fired, the WebSocket object can have several possible attributes that can be read in your client applications.
Attribute: readyState
Attribute: bufferedAmount
Attribute: protocol
Testing for WebSocket Support
For now, here is a quick way to check whether the API is supported on the client:
if (window.WebSocket) {
console.log("WebSocket: supported");
// ... code here for doing WebSocket stuff
} else {
console.log("WebSocket: unsupported");
// ... fallback mode, or error back to user
}
Reference
Books
