Client-side Web Sockets Application

Web Sockets API is as simple as below:

ws = new WebSocket(url, protocols);

Here are the explanations for this

  • url is the destination to connect. The URL scheme is either ws: or wss:. Many browsers only support insecure connections for local communications (such as localhost).
  • protocols [optional] is either a single string or an array of strings indicating sub-protocols accepted by the client. If it is not supplied, the server will receive an empty string.

Sending data to the server

ws.send("Hello from the client!");

Since client sockets may not be established when calling send, we usually put send inside an onopen event.

ws.onopen = function (event) {
  ws.send("Hello from the client!");
};

Note that you can use JSON.stringify to convert JSON objects to a string for communication.

Receiving data from the server

ws.onmessage = function (event) {
  console.log(event.data);
}

You can use JSON.parse to parse the data and convert it back JavaScript object.

Closing the connection

ws.close();

Note that you may want to check ws.bufferedAmount to ensure that all the data has been transmitted.