import ClientDriver from './client-driver.js' export default 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 } /* (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 = this.event.onconnected; /* (3) Bind callback.onclose */ this.ws.onclose = this.event.onclose; /* (4) Bind callback.onerror */ this.ws.onerror = this.event.onclose; /* (5) Bind callback.onreceive */ this.ws.onmessage = (_message_event) => this.event.onreceive(_message_event.data); /* (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' ){ this.state = ClientDriver.STATE.CONNECTED; return false; } /* (2) Send message */ this.ws.send(_request.buffer); /* (3) Return success */ return true; } /* (3) Closes the connection * * @return closed Whether the connection has been closed * ---------------------------------------------------------*/ close(){ /* (0) Parent check */ if( !super.close() ) return false; /* (1) Close websocket */ this.ws.close(); /* (2) Return success */ return true; } }