Answer: Please look into the below line of code segments (it is documented for easy understanding)
var webSocket;
//Step 1: Instantiate the WebSocket object
var webSocket = new WebSocket('ws://echo.websocket.org');
//check webSocket is not 'undefined and null'
if(!webSocket){
//Step 2: Check if the websocket is in OPEN state and henceforth the communication can be establish
if(webSocket.readyState == webSocket.OPEN){
//Step 3: Client send a message to the server once the connection opens
webSocket.send("Message from Client");
//Step 4: Server sends a response back to the client
webSocket.onmessage = function(e){
console.log("Message from Server" + e.data);
}
}
}
Asked In: Many Interviews |
Alert Moderator