Taro 微信小程序

417 阅读1分钟

web-view 与 小程序通讯 --- 使用socket进行通讯

步骤:

  • 1.小程序配置服务器域名(socket,tcp,request)、业务域名(webview的域名)

  • 2.集成socket.io socket.io/zh-CN/docs/… 下面有个专门对接小程序的库

image.png

跟进服务器版本选择对应的 weapp.socket.io 版本,集成项目中使用 克隆本地到处的方法集成

$ git clone https://github.com/weapp-socketio/weapp.socket.io

npm install

# development mode
#$ npm run build-dev

# production mode ---直接使用生环境的js文件
$ npm run build

$ cp path/weapp.socket.io/dist/weapp.socket.io.js path/your_weapp_dir
  • 3.使用
const io = require('./yout_path/weapp.socket.io.js')

const socket = io('https://socket-io-chat.now.sh')

socket.on('connect', () => {
  console.log('connection created.')
});

socket.on('new message', d => {
  const {
    username,
    message
  } = d;
  console.log('received: ', username, message)
});

socket.emit('add user', "Jack");
  • 4.消息传递 使用的是 mitt ,其他的也可以,使用 mitt 的emitter.off()时需要注意,任意一个地方emitter.off(xxx)方法了,其他任何 emitter.on(xxx)的地方都会失效