微信小程序 websocket+node.js(ws)
微信小程序webSocket的使用方法
服務器端使用nodejs配置
服務器這里用的是nodejs來配置,當然你也可以用其他后端語言來處理。假設你已經安裝好了nodejs,那么我們開始吧:
創建nodejs環境
引入ws模塊的構造函數並且實例化
監聽前端發送的消息
回發消息
(1)創建nodejs環境
首先新建一個文件夾websocket
window+R,輸入cmd
輸入cd 空格后將websocket直接拖拽到黑框內(或者cd 路徑)進入websocket文件夾
接着輸入npm install ws建立環境
回車之后就能看到目錄下生成了文件,環境就生成完畢,接下來就要寫服務端的代碼了
引入ws模塊的構造函數並且實例化
在websocket下創建一個文件server.js,用來編寫nodejs代碼,首先我們要引入ws模塊的構造函數並且實例化:
引入ws模塊的構造函數並且實例化:
//引入ws模塊的構造函數
var webSocketServer=require("ws").Server;
//實例化
var wss=new webSocketServer({
port:3001
});
(3)監聽前端發送的消息
繼續編寫server.js,監聽前端發送的消息:
wss.on(“connection”,function(ws)
ws.on(“message”,function(msg)
//引入ws模塊的構造函數
var webSocketServer=require("ws").Server;
//實例化
var wss=new webSocketServer({
port:3001
});
//監聽客戶端連接
wss.on("connection",function(ws){
console.log("服務器連接建立成功");
//監聽客戶端消息
ws.on("message",function(msg){
console.log(msg);
ws.send("來自客戶端的消息:"+msg);
})
});
(4)回發消息
服務器接收消息之后,還要具備回發消息的能力,給客戶端反饋消息,至於返回什么消息,不是我們這里要討論的,我們直接簡單的將客戶發送的消息回發回去即可:
ws.send(“來自客戶端的消息:”+msg)
//引入ws模塊的構造函數
var webSocketServer=require("ws").Server;
//實例化
var wss=new webSocketServer({
port:3001
});
//監聽客戶端連接
wss.on("connection",function(ws){
console.log("服務器連接建立成功");
//監聽客戶端消息
ws.on("message",function(msg){
console.log(msg);
ws.send("來自客戶端的消息:"+msg);
})
});
<!--pages/socket/socket.wxml-->
<!-- <text>pages/socket/socket.wxml</text>
<button bindtap="postdata">發送給后端</button> -->
<button bindtap="sendMessage">websocket</button>
<!-- <input bindchange="sendMessage" class="text" placeholder="請輸入消息"></input> -->
// pages/socket/socket.js
Page({
sendMessage: function () {
var socketOpen = false
//注冊信息
var data = { id:"666" }
var socketMsgQueue = JSON.stringify(data)
console.log(socketMsgQueue)
//建立連接
wx.connectSocket({
url: "ws://127.0.0.1:3001",
})
//
wx.onSocketOpen(function (res) {
console.log('WebSocket連接已打開!')
socketOpen = true
console.log('數據發送中' + socketMsgQueue)
sendSocketMessage(socketMsgQueue)
})
function sendSocketMessage(msg) {
if (socketOpen) {
wx.sendSocketMessage({
data: msg
})
} else {
socketMsgQueue.push(msg)
}
}
wx.onSocketError(function (res) {
console.log('WebSocket連接打開失敗,請檢查!')
})
wx.onSocketMessage(function (res) {
console.log('收到服務器內容:' + JSON.stringify(res))
})
}
})
//引入ws模塊的構造函數
var webSocketServer=require("ws").Server;
//實例化
var wss=new webSocketServer({
port:3001
});
//監聽客戶端連接
wss.on("connection",function(ws){
console.log("服務器連接建立成功");
//監聽客戶端消息
ws.on("message",function(msg){
console.log(msg);
ws.send("來自客戶端的消息:"+msg);
})
});