Pawan
Pawan

Reputation: 32331

Why websocket sendMessage is required

This is the code taken from the book "The Definitive Guide to HTML5 websocket"

div id="output"></div>
<script>
function setup() {
output = document.getElementById("output");
ws = new WebSocket("ws://localhost:7777");

ws.onopen = function(e) {
    log("Connected");
    sendMessage("Hello Websocket!");
}

ws.onclose = function(e){
    log("Disconnected: " + e.reason);
}

ws.onerror = function(e){
    log("Error ");
}

ws.onmessage = function(e) {
    log("Message received: " + e.data);
    ws.close();
}

}

function sendMessage(msg){
ws.send(msg);
    log("Message Sent");
}

function log(s){
var p = document.createElement("p");
p.style.wordWrap = "break-word";

Could anybody please let me know for what reason this below event is required ??.

 ws.send(msg);

I understand that the below will call the onMessage method on server side as shown below

public void onMessage(String data) {

}

But the actual purpose of onMessage on server side is to send data from backend to the javascript which will inturn call onmessage of client side javascript .

could anybody please help me understand this .

Upvotes: 0

Views: 59

Answers (1)

Ambarish
Ambarish

Reputation: 1675

In the above code the ws.onopen, ws.onclose, ws.onmessage are all events associated with WebSocket object.

Whereas ws.send() is a method associated with WebSocket object. There is a huge difference between them.

The following event ensures that the Web Socket is connected to the server i.e you've opened your connection

ws.onopen = function(e) {
    //Once you've opened your connection
    //you can begin transmitting data to the server 
    //using the following method
    ws.send("You\'re message");
}

So the main purpose of ws.send() method is to transmit data from the client to the server which is done by simply calling the WebSocket object's send() [in your case ws.send(msg)].

And also send data only takes place once a connection is established with the server by defining an onopen event handler.

Upvotes: 1

Related Questions