是可能的,我们可以有多个处理程序(onmessage方法)为相同的webcocket会话?在下面的代码中,只有一个onmessage方法来处理来自客户端的消息。但是是否有可能,我们可以有多个onmessage处理方法为同一个websocket会话?
代码: 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
});
};
WebSocket
对象支持.addEventListener()
,所以您可以这样做:
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
});