Socket.weapp.js 587 B

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