Use Generic EventListener Interface with WebSocket
<!DOCTYPE HTML> <html> <head> <title>Canvas Demo</title> </head> /*from w ww. jav a 2s.c o m*/ <body> <h1>Web Sockets Demonstration</h1> <script> let chatUrl = 'ws://www.your server.com/chat '; let validProtocols = ['chat', 'json']; let chatSocket = new WebSocket(chatUrl, validProtocols); function CreateWebSocketEventObject() { this.handleError_ = function() { console.log('An error occurred on the chat connection.'); }; this.handleClose_ = function(event) { console.log('The chat connection was closed because ', event.reason); }; this.handleOpen_ = function(event) { console.log('The chat connection is open.'); }; this.handleMessage_ = function(event) { console.log('A message event has been sent.'); if (chatSocket.protocol === validProtocols[0]) { console.log('The chat protocol is active.'); console.log('The data the server transmitted is: ', event.data); } else { console.log('The json protocol is active.'); console.log('The data the server transmitted is: ', event.data); } }; this.handleEvent = function(event) { switch (event.type) { case 'error': this.handleError_(); break; case 'close': this.handleClose_(event); break; case 'open': this.handleOpen_(event); break; case 'message': this.handleMessage_(event); break; default: console.warn('Unknown event of type ', event.type); } }; } let eventHandlerObject = new CreateWebSocketEventObject(); chatSocket.addEventListener('error', eventHandlerObject); chatSocket.addEventListener('close', eventHandlerObject); chatSocket.addEventListener('open', eventHandlerObject); chatSocket.addEventListener('message', eventHandlerObject); </script> </body> </html>