Socket.weapp.js 602 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. "use strict";
  2. module.exports = class {
  3. constructor(serverURL) {
  4. this.onopen = () => {};
  5. this.onmessage = () => {};
  6. this.onclose = () => {};
  7. this.onerror = () => {};
  8. wx.connectSocket({
  9. url: serverURL
  10. });
  11. wx.onSocketOpen(() => {
  12. this.onopen();
  13. });
  14. wx.onSocketMessage(msg => {
  15. this.onmessage(msg);
  16. });
  17. wx.onSocketClose(() => {
  18. this.onclose();
  19. });
  20. wx.onSocketError(error => {
  21. this.onerror(error);
  22. });
  23. }
  24. send(data) {
  25. wx.sendSocketMessage({
  26. data
  27. });
  28. }
  29. close() {
  30. wx.closeSocket();
  31. }
  32. };