websocket.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // 获取应用实例
  2. const app = getApp();
  3. Page({
  4. data: {
  5. appid: 'aaaaaaaa',
  6. websocketServer: '开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名',
  7. sendMessageAbility: false,
  8. toSendMessage: 'test',
  9. closeLinkAbility: false,
  10. log: '',
  11. },
  12. onLoad() {
  13. // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调
  14. my.onSocketClose((res) => {
  15. my.alert({content: '连接已关闭!'});
  16. this.setData({
  17. sendMessageAbility: false,
  18. closeLinkAbility: false,
  19. });
  20. });
  21. // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调
  22. my.onSocketOpen((res) => {
  23. my.alert({content: '连接已打开!'});
  24. this.setData({
  25. sendMessageAbility: true,
  26. closeLinkAbility: true,
  27. });
  28. });
  29. my.onSocketError(function(res){
  30. my.alert('WebSocket 连接打开失败,请检查!' + res);
  31. });
  32. // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调
  33. my.onSocketMessage((res) => {
  34. my.alert({content: '收到数据!' + JSON.stringify(res)});
  35. });
  36. },
  37. onServerAddressComplete(e) {
  38. this.setData({
  39. websocketServer:e.detail.value,
  40. });
  41. },
  42. onSendMessageReady(e) {
  43. this.setData({
  44. toSendMessage:e.detail.value,
  45. });
  46. },
  47. connect_start() {
  48. my.connectSocket({
  49. url: this.data.websocketServer, // 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名
  50. success: (res) => {
  51. my.showToast({
  52. content: 'success', // 文字内容
  53. });
  54. },
  55. fail:()=>{
  56. my.showToast({
  57. content: 'fail', // 文字内容
  58. });
  59. }
  60. });
  61. },
  62. send_start() {
  63. my.sendSocketMessage({
  64. data: this.data.toSendMessage, // 需要发送的内容
  65. success: (res) => {
  66. my.alert({content: '数据发送!' + this.data.toSendMessage});
  67. },
  68. });
  69. },
  70. close_start() {
  71. my.closeSocket();
  72. },
  73. });