小程序模板网

微信小程序聊天室(websocket )(PHP)

2018-04-17 二烯烃

作者:奋斗放个,来自原文地址 
//utils文件夹下websoctet.js文件

 

  1. var url = 'ws://地址端口';
  2.  
  3. function connect(user, func) {
  4.  
  5. wx.connectSocket({
  6. url: url,
  7. header: {"content-type":'application/x-www-form-urlencoded'}
  8. });
  9. wx.onSocketOpen(function (res) {
  10. send('{"type":"login","client_name":"'+user.nickName+'","room_id":"1"}')
  11. });
  12. //接受消息
  13. wx.onSocketMessage(func);
  14. }
  15.  
  16. //发送消息
  17. function send(msg) {
  18. wx.sendSocketMessage({ data: msg });
  19. }
  20. module.exports = {
  21. connect: connect,
  22. send: send
  23. }

//具体页面.js文件内容:

 

  1.  
  2. var websocket = require('../../utils/websocket.js');
  3. //事件处理函数
  4. add: function (e) {
  5. websocket.send('{"type":"say","from_client_id":"'+user.nickName+'","to_client_id":"all","content":"'+this.data.message+'"}')
  6. },
  7. onLoad: function () {
  8. var that = this
  9. //调用应用实例的方法获取全局数据
  10. app.getUserInfo(function (userInfo) {
  11. user = userInfo;
  12. websocket.connect(user, function (res) {
  13. text = that.encodeStr(res.data) + "\n";
  14. console.log(res)
  15. that.setData({
  16. text: text
  17. });
  18. // websocket.send('{"type":"pong"}');
  19. })
  20. })
  21. },

//下面方法很好玩,因为使用的服务器 是开源的PHP服务器,所以微信小程序接收到的聊天室中文内容是ASCII编码,所以经过此方法可以转换。

 

  1. encodeStr: function (str) {
  2. var character = str.split("\\u");
  3. var native1 = character[0];
  4. for (var i = 1; i < character.length; i++) {
  5. var code = character[i];
  6. native1 += String.fromCharCode(parseInt("0x" + code.substring(0, 4)));
  7. if (code.length > 4) {
  8. native1 += code.substring(4, code.length);
  9. }
  10. }
  11. return native1
  12. },


易优小程序(企业版)+灵活api+前后代码开源 码云仓库:starfork
本文地址:https://www.eyoucms.com/wxmini/doc/course/23537.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询