uni-app uniapp的websocket是否可以实现浏览器的websocket规范,这样可以使用许多实用的websocket库而非自实现

rjee0c15  于 8个月前  发布在  uni-app
关注(0)|答案(2)|浏览(206)

新功能描述
uniapp的websocket是否可以实现浏览器的websocket规范

参考链接:

现状及问题

一些常见的websocket库时无法使用,如graphql-ws

尝试方案

尝试了做适配器,但没成功,会显示子协议不支持

补充信息

https://juejin.cn/post/7225074892357337148#comment

jgzswidk

jgzswidk1#

可以封装(难易度:★★★☆☆),但我希望社区的开发者们能动起来,相关可以参考这个对localstorage的封装: https://github.com/zhetengbiji/mp-storage

gudnpqoy

gudnpqoy2#

可以封装(难度:★★★☆☆),但我希望社区的开发者能动起来,相关可以参考这个对localstorage的封装: https://github.com/zhetengbiji/mp-storage

如下是我实现的一部分,但能力有限,好像在使用其他库时还有点问题,,正处于调试中:

  1. export class uniWebSocket {
  2. private socketTask: null | UniApp.SocketTask;
  3. public readyState: number = 0;
  4. constructor(url: string, protocol: string) {
  5. const socketTask = uni.connectSocket({
  6. url,
  7. protocols: [protocol],
  8. complete: () => {},
  9. });
  10. this.socketTask = socketTask;
  11. if (!this.socketTask) {
  12. throw new Error("server didn't accept Websocket");
  13. }
  14. }
  15. static CONNECTING = 0;
  16. static OPEN = 1;
  17. static CLOSING = 2;
  18. static CLOSED = 3;
  19. addEventListener(type: "open" | "error" | "close" | "message", callback: (event: any) => void) {
  20. if (this.socketTask === null) throw new Error("uniWebSocket not init");
  21. if (type === "open") {
  22. this.socketTask.onOpen((e: any) => {
  23. console.log("websocket连接打开");
  24. this.readyState = 1;
  25. callback(e);
  26. });
  27. } else if (type === "error") {
  28. this.socketTask.onError((e: any) => {
  29. console.log("websocket连接错误");
  30. this.readyState = 1;
  31. callback(e);
  32. });
  33. } else if (type === "close") {
  34. this.socketTask.onClose((e: any) => {
  35. console.log("websocket连接关闭");
  36. this.readyState = 2;
  37. callback(e);
  38. this.readyState = 3;
  39. });
  40. } else if (type === "message") {
  41. this.socketTask.onMessage((e: any) => {
  42. console.log("websocket消息接收: ", e);
  43. this.readyState = 1;
  44. callback(e);
  45. });
  46. }
  47. }
  48. public send(msg: string) {
  49. if (this.socketTask === null) throw new Error("uniWebSocket not init");
  50. this.socketTask.send({ data: msg });
  51. }
  52. public close(code: number, reason: string) {
  53. if (this.socketTask === null) throw new Error("uniWebSocket not init");
  54. this.socketTask.close({ code, reason });
  55. }
  56. }
展开查看全部

相关问题