微信小程序 聊天室简单实现
utils文件夹下websoctet.js文件
var url = 'ws://地址端口'; function connect(user, func) { wx.connectSocket({ url: url, header: {"content-type":'application/x-www-form-urlencoded'} }); wx.onSocketOpen(function (res) { send('{"type":"login","client_name":"'+user.nickName+'","room_id":"1"}') }); //接受消息 wx.onSocketMessage(func); } //发送消息 function send(msg) { wx.sendSocketMessage({ data: msg }); } module.exports = { connect: connect, send: send }
具体页面.js文件内容:
var websocket = require('../../utils/websocket.js'); //事件处理函数 add: function (e) { websocket.send('{"type":"say","from_client_id":"'+user.nickName+'","to_client_id":"all","content":"'+this.data.message+'"}') }, onLoad: function () { var that = this //调用应用实例的方法获取全局数据 app.getUserInfo(function (userInfo) { user = userInfo; websocket.connect(user, function (res) { text = that.encodeStr(res.data) + "\n"; console.log(res) that.setData({ text: text }); // websocket.send('{"type":"pong"}'); }) }) },
下面方法很好玩,因为使用的服务器 是开源的PHP服务器,所以微信小程序接收到的聊天室中文内容是ASCII编码,所以经过此方法可以转换。
encodeStr: function (str) { var character = str.split("\\u"); var native1 = character[0]; for (var i = 1; i < character.length; i++) { var code = character[i]; native1 += String.fromCharCode(parseInt("0x" + code.substring(0, 4))); if (code.length > 4) { native1 += code.substring(4, code.length); } } return native1 },
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!