Socket.weapp.js 603 B

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