微信小程序WebSocket

1 服务端

npm init -y
npm i ws --save

2  服务端

const WebSocket = require('ws');

const wss = new WebSocket.Server({
  port: 8080
});
let stocks ={ruanmou:100,tencent:100,JD:50}

function randomInterval(min,max){
	return Math.floor(Math.random()*(max-min+1)+min)
}
function randomStockUpdater(){
	for (let stock in stocks) {
	  let randomValu = randomInterval(-50,50)/100
	  stocks[stock] = new Number((stocks[stock]+randomValu).toFixed(2))
	}
	setTimeout(()=>{
		randomStockUpdater()
	},3000)
}
randomStockUpdater()

//微信发送数据
wss.on("connection",res=>{
setInterval(()=>{
		res.send(JSON.stringify(stocks))
},300)
})

微信客户端

wxml


    

wxjs

let socket
Page({
    data: {
        
    },
    onLoad: function(options) {
        //Do some initialize when page load.
        
    },
    connect:function(){
        socket= wx.connectSocket({
            url: 'ws://localhost:8080',
            success: function(res) {
                // console.log(res)
            }
        })

        socket.onMessage(result => {
            console.log(result)
        });
          
    }
})

 

你可能感兴趣的:(wxxm)