WebSocketTransport.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * Copyright 2018 Google Inc. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. const WebSocket = require('ws');
  17. /**
  18. * @implements {!Puppeteer.ConnectionTransport}
  19. */
  20. class WebSocketTransport {
  21. /**
  22. * @param {string} url
  23. * @return {!Promise<!WebSocketTransport>}
  24. */
  25. static create(url) {
  26. return new Promise((resolve, reject) => {
  27. const ws = new WebSocket(url, [], {
  28. perMessageDeflate: false,
  29. maxPayload: 256 * 1024 * 1024, // 256Mb
  30. });
  31. ws.addEventListener('open', () => resolve(new WebSocketTransport(ws)));
  32. ws.addEventListener('error', reject);
  33. });
  34. }
  35. /**
  36. * @param {!WebSocket} ws
  37. */
  38. constructor(ws) {
  39. this._ws = ws;
  40. this._ws.addEventListener('message', event => {
  41. if (this.onmessage)
  42. this.onmessage.call(null, event.data);
  43. });
  44. this._ws.addEventListener('close', event => {
  45. if (this.onclose)
  46. this.onclose.call(null);
  47. });
  48. // Silently ignore all errors - we don't know what to do with them.
  49. this._ws.addEventListener('error', () => {});
  50. this.onmessage = null;
  51. this.onclose = null;
  52. }
  53. /**
  54. * @param {string} message
  55. */
  56. send(message) {
  57. this._ws.send(message);
  58. }
  59. close() {
  60. this._ws.close();
  61. }
  62. }
  63. module.exports = WebSocketTransport;