It always feels weird to implement the chat function on a small program in WeChat, a chat tool. But the leader asked for it, always do it.
Then on the real-time communication of this keyword to start searching, shuttling between the pages. But paste and copy really too much, looking for half a day did not find what I want, but still extracted the keywords WebSocket and the, and then search for these two is what, what is the relationship, finally understand a little.
Finally it was determined that the first step that needed to be done was to use the build service (I installed it under my own windows):
1. First of all, go to the official website to downloaddownload link
Installation is very simple, double-click the downloaded file, directly next step, nothing special to choose, the path default is good!
You can open a command line window and type node -v which will output the version to check whether the installation was successful or not.
2. Then create a new folder (I installed mine on the Ç drive, and then created a new folder called webSocket under the d drive)
Then go to that directory with the command: under this file install the module we want to use: you need to generate a configuration file before installing the module, otherwise you will report an error (I reported it anyway)
Generate Configuration File command:npm init -f
After the execution of the file can be seen in the file called under the configuration file, do not worry about it (the back also did not care about it), then continue to install the module operations
I installed it at first, but then realized that the applet doesn't work at all, so I won't go into that here. We use ws here.
Install the ws command:npm install --save ws
(Uninstall module command: npm uninstall module name)
3. After installing the module, create a .js file in your directory, I've got a
I'm sure I'll have more paperwork here than you guys, don't worry about it.
Then open this .js file and start editing your server-side code, which you can do with Notepad or whatever.
This is the simplest and most basic piece of code that opens a connection and responds:
//Introduce the ws module const WebSocket = require('ws'); //create the service port is the port const wss = new ({ port: 80}); //This is what happens when the client connects. ('connection', function connection(ws) { ('Connection successful'); //This is triggered when the client sends a message ('message', function incoming(data) { ('Message received'); //data is the message sent by the client, here it is broadcast to all clients (function each(client) { //Take the data from the client and send it to each client in a loop. (data); }); }); });
Here to post a slightly more complete code, here is to use the database to save the sent messages, using mysql, so you need to install the mysql module in the
npm install --save mysql
Code:
There's a lot of commented code here, all of which I used when I was drumming, so you can ignore it or delete it
This MySQL data connection needs to be modified to suit your own, and the table
The table I'm using here has just two fields, id and msg.
var http=require('http'); var qs = require('querystring'); // var ws=require('ws'); var server=(function (req, res) { ("This is a WebSockets server!"); }); var url = require('url'); // Validation Functions function ClientVerify(info) { var ret = false;// Rejected //url parameters var params = (, true).query; //(groupid); //groupid=params['groupid'] /whoever came to the discussion group // (function each(client) { // ('233'); // }); return true; } var wss = new ( { server: server,verifyClient: ClientVerify } ); /*// Introduce the database var mysql = require('mysql'); // Connection database information Normal version var connection = ({ host : '58.87.94.16', user : 'root', password : 'root', database : 'bootdo' });*/ // Introducing a database var mysql = require('mysql'); // Create data pools const pool = ({ host : '58.87.94.16', // Database address user : 'root', // Database users password : 'root', // Database password database : 'bootdo' // Selected databases }) /* Receives a sql statement and the required values. The reason for taking the second parameter values here is that you can use mysql's placeholders '?' For example query(`select * from my_database where id = ? `, [1]) Seems to work directly, not sure yet */ let query = function(sql,values,callback){ (function(err,conn){ if(err){ callback(err,null,null); }else{ (sql,values,function(err,results,fields){ //Release connection (); //Event-driven callbacks callback(err,results,fields); }); } }); }; =query; ('connection', function connection(ws) { ('Link successful!'); //(ws); // Query history of chats Broadcast to connected clients var sql='select * from hi_test where groupid=1'; ('sql statement',sql); query(sql,function (err,res,fields) { ('The sql operation returns:', res); if(res!=null){ ((res)); } }); // Listen for messages from the client. ('message', function incoming(data) { ('Message from client:',data); //Save messages sent by the client to the database sql="insert into hi_test(msg) values(?)"; ('sql statement',sql); query(sql,data,function (err,res,fields) { ('The sql operation returns:',res);// }); var sendData=([{msg:data}]) /** * Send the message to all clients * Get all linked clients */ (function each(client) { (sendData); }); }); }); (80, function listening() { ('Server started successfully!'); }); /*propose sth (for the first time)getrequesting var options = { hostname: '', path: '/attendanceParameter/getAttendanceParameter/13', method: 'GET' }; var req = (options, function (res) { ('Status: ' + ); ('data', function (chunk) { ('Return data: ' + chunk); }); }); ('error', function (e) { ('problem with request: ' + ); }); ();*/ /* /! * Build the http service *! / var app = require('http').createServer() /! * Introduce *! / var io = require('')(app); /! * Define listening port, can be customized, port should not be occupied *! / var PORT = 80; /! *Listening port *! /! (PORT); /! * Define the user array *! /! var users = []; /! /! /! * Listening for client connections *io is the server-side socket we defined. ** The socket in the callback function is the client socket for this connection. ** io and socket have a one-to-many relationship. *! /! ('connection', function (socket) { /! * All listening on, and sending emit must be written inside the connection, including disconnecting *! /! ('login', function (data){ ('Someone has logged in:') (data); ({ username. }); /! * Broadcast the add event to all connected clients *! /! ('add',data) }) }) ('app listen at'+PORT);*/
Then type node (your own filename) at the command line and enter, and the service has started!
4. Now the service has been up, the next get small program this side of the
Post the code directly:
wxml:
<view class='homeView'> <scroll-view scroll-y style="height:500px;" scroll-top='{{scrolltop}}'> <view class='listView'> <block wx:for="{{serverMsg}}" wx:key='*this'> <!-- --> <view wx:if="{{!=}}" class='leftView'> <view class='name'>{{}}</view> <view class='imgmsgleft'> <view> <!-- I'm using a picture from another service I own. --> <image class='touimg' src='/static/images/'></image> </view> <view>{{}}</view> </view> </view> <view wx:else class='rightView'> <view class='name'>{{}}</view> <view class='imgmsg'> <view>{{}}</view> <view> <!-- I'm using a picture from another service I own. --> <image class='touimg' src='/static/images/'></image> </view> </view> </view> </block> </view> </scroll-view> <view class='sendView'> <input bindinput='sendTextBind' placeholder="Enter chat." value='{{sendText}}' /> <button bindtap='sendBtn' type="primary">dispatch</button> </view> </view>
js:
var app = getApp(); Page({ data: { socket_open: false,//Judge whether the connection is open or not sendText: "",// Messages sent serverMsg: [],//Accepted server-side messages userInfo: { userId: 1, name: "Huh.",img:'Avatar'},//, scrolltop: 999 }, /** Input content */ sendTextBind: function(e) { ({ sendText: }); (); }, /**Send a message */ sendBtn: function(e) { ('Send message event!'); var msgJson = { user: { id: ,//, // Unique ID to distinguish identity name: , //Display with name img: , //Display with avatar }, msg: ,// Messages sent groupid:1 } //Send a message this.send_socket_message((msgJson)); ({ sendText: ""//Empty the text box after sending the message }); }, onLoad: function(options) { // (); // ({ // userInfo: // }); //Initialization (); }, wssInit() { var that = this; // Establishment of connection ({ url: 'ws://localhost'// }) // Listen for the WebSocket connection open event. (function(res) { ('WebSocket connection is open!'); ({ socket_open: true }); }); // Listen for events when WebSocket receives a message from the server. (function(res) { ('Received server content:', res); var server_msg = (); (server_msg); if (server_msg != null) { var msgnew = []; for (var i = 0; i < server_msg.length; i++) { ((server_msg[i].msg)); } msgnew=(msgnew); ({ serverMsg: msgnew, scrolltop: * 100 }); (); } }); // Listen for WebSocket errors. (function(res) { ('WebSocket connection failed to open, please check!', res) }); }, send_socket_message: function(msg) { //socket_open, the connection is opened after the callback will be true, then can send the message if (.socket_open) { ({ data: msg }) } } })
wxss:
.homeView { border-top: 1px solid #ededed; } .listView{ padding-bottom: 50px; } .listView>view { padding: 10px; } .rightView { text-align: right; } .imgmsgleft { display: flex; justify-content: flex-start; align-items: center; } .imgmsgleft>view:last-child { border: solid 1px gray; padding: 10px; border-radius: 6px; } .imgmsg { display: flex; justify-content: flex-end; align-items: center; } .imgmsg>view:first-child { border: solid 1px gray; padding: 10px; border-radius: 6px; background-color: green; } .touimg { width: 50px; height: 50px; } .name { font-size: 14px; color: gray; } .sendView { display: flex; width: 100%; position: fixed; bottom: 0px; border-top: 1px #ededed solid; background-color: white; } .sendView>button { width: 20%; } .sendView>input { width: 80%; height: auto; }
Rendering:
Be sure to turn on debugging when previewing, as this isn't a WSS protocol and won't work directly,
summarize
The above is a small introduction to the use of the implementation of WeChat small program real-time chat function, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. I would also like to thank you very much for your support of my website!