Simple implementation of WeChat mini-app chat rooms and Wechat mini-app chat rooms

Source: Internet
Author: User
Tags php server

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.