Simple implementation of mini-program chat rooms
Simple implementation of mini-program chat rooms
The websoctet. js file in the utils folder
Var url = 'ws: // address port '; 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 "}')}); // receives the message wx. onSocketMessage (func);} // send the message function send (msg) {wx. sendSocketMessage ({data: msg});} module. exports = {connect: connect, send: send}
Specific page. js file content:
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 // call the method of the application instance to obtain the global data 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 "}');})})},
The following method is very interesting. Because the server used is an open-source PHP server, the Chinese content of the chat room received by the applet is ASCII, so this method can be converted.
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 },
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!