Communicating the Websocket Using Javascript

Posted By : Pranav Kakkar | 27-Jul-2019

In order to communicate using the WebSocket protocol, you need to make a WebSocket object; this can automatically commit to open the connection to the server.

The WebSocket constructor accepts the one required and the one optional parameter:

webSocket = new WebSocket(url, protocols);

URL

The URL to which to connect; this could be the URL to which the WebSocket server can respond. this could use the URL scheme wss://, though some software might permit you to use the insecure ws:// for native connections.

Protocols

Either one protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, in order that a single server will implement multiple WebSocket sub-protocols (for example, you may wish one server to be able to handle differing kinds of interactions counting on the required protocol). If you do not specify a protocol string, associate empty string is assumed.
The builder can throw a SecurityError if the destination does not permit access. this could happen if you arrange to use associate insecure association (most user agents currently need a secure link for all WebSocket connections unless they are on an equivalent device or probably on an equivalent network).


Connection errors

If a blunder happens whereas making an attempt to attach, initial an easy event with the name error is distributed to the WebSocket object (thereby invoking its onerror handler), so the CloseEvent is distributed to the WebSocket object (thereby invoking its onclose handler) to point the rationale for the connection's closing.

Examples

This simple example creates a replacement WebSocket, connecting to the server at wss://www.example.com/socketserver. A custom protocol of "protocolOne" is known as within the request for the socket during this example, tho' this could be omitted.

var socketExample = new webSocketConnection("wss://www.sampleExample.com/socketserverConnect", "protocolOne");

On return, exampleSocket.readyState is CONNECTING. The readyState can become OPEN once the association is prepared to transfer information.

If you would like to open a association and square measure versatile concerning the protocols you support, you'll specify associate array of protocols:

var socketExample = new webSocketConnection("wss://www.sampleExample.com/socketserverConnect", ["protocolOne", "protocolTwo"]);

Once the association is established (that is, readyState is OPEN), exampleSocket.protocol can tell you which of them protocol the server elect.

Establishing a WebSocket depends on the hypertext transfer protocol Upgrade mechanism, therefore the request for the protocol upgrade is implicit after we address the net server as ws://www.example.com or wss://www.example.com.

 

Sending information to the server

 

Once you have opened your association, you'll begin transmission information to the server. To do this, merely decision the WebSocket object's send() methodology for every message you would like to send:

socketExample.send("Here's some text that the server is urgently awaiting!");

You can send information as a string, Blob, or ArrayBuffer.

As establishing a association is asynchronous and at risk of failure there's no guarantee that career the send() methodology instantly once making a WebSocket object are sure-fire. we are able to a minimum of make sure that {attempting|trying|making associate attempt} to send information solely takes place once a association is established by shaping an onopen event handler to try to to the work:

socketExample.onopen = function (event) {
  socketExample.send("Message that server Needs!"); 
};

Using JSON to transmit objects

One handy factor you'll do is use JSON to send fairly complicated information to the server. for instance, a conversation program will act with a server employing a protocol enforced exploitation packets of JSON-encapsulated data:

function sendTextToServer() {
  var msgToSend = {
    type: "message",
    text: document.getElementById("txt").value,
    id:   clientsID,
    date: Date.now()
  };
  exampleSocket.send(JSON.stringify(msgToSend));
  document.getElementById("txt").value = "";
}

About Author

Author Image
Pranav Kakkar

Pranav is a sharp intellectual UI Developer, he has a good Knowledge of HTML, CSS. His hobbies are Playing Cricket, Football, listening Music.

Request for Proposal

Name is required

Comment is required

Sending message..