Can u please explain with a very basic example as how cilent-server communication happens via WebSocket

 Posted by Rajnilari2015 on 9/19/2015 | Category: HTML 5 Interview questions | Views: 381 | Points: 40
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 

Comments or Responses

Login to post response