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
});
};
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With