Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Handlers for Websocket Javascript

Is that possible that we can have multiple handlers (onmessage method) for same webcocket session? In the below code there is only one onmessage method to handle a message from the client. But is there any possibility that we can have multiple onmessage handler methods for same websocket session ?

Code:

    var url = window.location.href;
    var arr = url.split("/");
    var redirectURL = arr[0] + "//" + arr[2];
    var wsURL = redirectURL.replace('http','ws');
    var ws = new WebSocket(wsURL+'/abc');
    ws.onopen = function(event) {
        var data = '{"userId":' + sessionStorage.getItem('userID') + '}';
        ws.send((data));
    };

    ws.onmessage = function(event) {
        var msg = event.data;
        console.info('Push Message : ' + msg);
        Ext.toast({
             html: msg,
             title: 'Alert',
             align: 'br',
             autoShow : true
        });

    };
like image 499
Vaibhav Maniar Avatar asked Aug 29 '16 16:08

Vaibhav Maniar


1 Answers

The WebSocket object supports .addEventListener() so, you can do this:

var url = window.location.href;
var arr = url.split("/");
var redirectURL = arr[0] + "//" + arr[2];
var wsURL = redirectURL.replace('http','ws');
var ws = new WebSocket(wsURL+'/abc');
ws.addEventListener("open", function(event) {
    var data = '{"userId":' + sessionStorage.getItem('userID') + '}';
    ws.send((data));
});

ws.addEventListener("message", function(event) {
    var msg = event.data;
    console.info('Push Message : ' + msg);
    Ext.toast({
         html: msg,
         title: 'Alert',
         align: 'br',
         autoShow : true
    });

});

// some other listener for incoming messages
ws.addEventListener("message", function(event) {
    // code here
});
like image 96
jfriend00 Avatar answered Oct 24 '22 07:10

jfriend00