Introduction to SockJS

Under the hood, the SockJS client will try to use the native WebSocket that the browser provides. If it is not available, it will fall back to other transport protocols, such as XHR-Streaming and  XHR-Polling. Its API is very simple to use. The following is an example of establishing a WebSocket connection with a local server at the /rt path:

let socket = new SockJS('http://localhost:8080/rt')
socket.onopen = function (event) {
// Connection established
console.log(socket.readyState)
}

socket.onmessage = function (message) {
// Message received via WebSocket
}

socket.onclose = function (event) {
// Connection closed
}

socket.onerror = function (error) {
// An error occurred
}

As you can see, it has four event handlers:

  • The onopen() event handler will be invoked when the connection to the server has been established. At this stage, the readyState property of the SockJS object has been changed from SockJS.COLLECTING to SockJS.OPEN.
  • The onmessage() event handler will be invoked when the client receives a message from the server side.
  • The onclose() event handler will be invoked when the WebSocket connection has been closed.
  • The onerror() event handler will be invoked when an error occurs.

Besides these event handlers, SockJS provides the send() method for the client to send data to the server. The API is quite simple. It looks like this:

socket.send(data)

The data can be a string, blob, ArrayBuffer, or ArrayBufferView.  

Also, SockJS provides a close() method for the client to close the connection from the server, as follows:

socket.close()

The biggest advantage of SockJS is that its API follows the HTML5 WebSocket API closely. It provides a generic base layer for applications to build their own communication modes. If you are interested in the latest WebSocket API specification, you can find it here: https://html.spec.whatwg.org/multipage/web-sockets.html.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.53.93