import {ClientDriver} from './client-driver.js' export class WebSocketClientDriver extends ClientDriver{ /* (1) Creates a client driver * * @_resource Target resource (typically an URL) * ---------------------------------------------------------*/ constructor(_resource){ /* (0) Parent check */ if( !super().error ) return; /* (1) Set inherited attributes */ this.resource = _resource; /* (2) Create useful attributes */ this.ws = null; this.buffer = null; // useful when waiting for WebSocket to open /* (N) Set all is ok */ this.error = false; } /* (2) Binds the client to the resource * * @return bound Whether the binding has been successful * ---------------------------------------------------------*/ bind(){ /* (0) Parent check */ if( !super.bind() ) return false; /* (1) Create WebSocket client instance */ this.ws = new WebSocket(this.resource); /* (2) Bind callback.onready */ this.ws.onopen = function(){ this.state = ClientDriver.STATE.CONNECTED; this.callback.onready(); }.bind(this); /* (3) Bind callback.onclose */ this.ws.onclose = function(){ this.state = ClientDriver.STATE.CLOSED; this.callback.onclose(); }.bind(this); /* (4) Bind callback.onerror */ this.ws.onerror = function(){ this.state = ClientDriver.STATE.CLOSED; this.callback.onclose(); }.bind(this); /* (5) Bind callback.onreceive */ this.ws.onmessage = function(response){ this.state = ClientDriver.STATE.CONNECTED; this.callback.onreceive(response); }.bind(this); /* (6) Return success */ return true; } /* (3) Send request * * @_request Request data * * @return sent Whether the request has been successful * ---------------------------------------------------------*/ send(_request){ /* (0) Parent check */ if( !super.send(_request) ) return false; /* (1) Error: invalid _request.buffer */ if( typeof _request.buffer !== 'string' ) return false; /* (2) Send message */ console.log('sent', _request.buffer); this.ws.send(_request.buffer); /* (3) Return success */ return true; } /* (4) Bind event to connection opened * * @_callback Callback launched when connection is opened * * @return bound Whether the callback has successfully been bound * ---------------------------------------------------------*/ onready(_callback){ /* (0) Parent check */ if( !super.onready(_callback) ) return false; } /* (5) Bind event to connection closed * * @_callback Callback launched when connection is closed * * @return bound Whether the callback has successfully been bound * ---------------------------------------------------------*/ onclose(_callback){ /* (0) Parent check */ if( !super.onclose(_callback) ) return false; } /* (6) Bind event to message reception * * @_callback Callback launched when a message is received * * @return bound Whether the callback has successfully been bound * ---------------------------------------------------------*/ onreceive(_callback){ /* (0) Parent check */ if( !super.onreceive(_callback) ) return false; } }