uniapp,h5

websocket.node.js 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { WebSocket } from "ws";
  2. import { BaseWS } from "./websocket.js";
  3. /**
  4. * WebSocket transport based on the `WebSocket` object provided by the `ws` package.
  5. *
  6. * Usage: Node.js, Deno (compat), Bun (compat)
  7. *
  8. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
  9. * @see https://caniuse.com/mdn-api_websocket
  10. */
  11. export class WS extends BaseWS {
  12. createSocket(uri, protocols, opts) {
  13. var _a;
  14. if ((_a = this.socket) === null || _a === void 0 ? void 0 : _a._cookieJar) {
  15. opts.headers = opts.headers || {};
  16. opts.headers.cookie =
  17. typeof opts.headers.cookie === "string"
  18. ? [opts.headers.cookie]
  19. : opts.headers.cookie || [];
  20. for (const [name, cookie] of this.socket._cookieJar.cookies) {
  21. opts.headers.cookie.push(`${name}=${cookie.value}`);
  22. }
  23. }
  24. return new WebSocket(uri, protocols, opts);
  25. }
  26. doWrite(packet, data) {
  27. const opts = {};
  28. if (packet.options) {
  29. opts.compress = packet.options.compress;
  30. }
  31. if (this.opts.perMessageDeflate) {
  32. const len =
  33. // @ts-ignore
  34. "string" === typeof data ? Buffer.byteLength(data) : data.length;
  35. if (len < this.opts.perMessageDeflate.threshold) {
  36. opts.compress = false;
  37. }
  38. }
  39. this.ws.send(data, opts);
  40. }
  41. }